而當固定右端點 r 時,我們的目標是找到最大的 s[r]−s[l−1],這等同找到最小的 s[l−1]。故我們可以枚舉右端點、維護左端點,也就是一邊計算前綴和 s[r] 一邊維護最小的 s[l−1],如此便可以在 O(n) 時間內求解。
複雜度分析
時間複雜度:O(n),其中 n 是陣列的長度。
空間複雜度:O(1)。
1 2 3 4 5 6 7 8 9
classSolution: defmaxSubArray(self, nums: List[int]) -> int: ans = float('-inf') s = mn = 0 for x in nums: s += x ans = max(ans, s - mn) mn = min(mn, s) return ans
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intmaxSubArray(vector<int>& nums){ int ans = INT_MIN, s = 0, mn = 0; for (int x : nums) { s += x; ans = max(ans, s - mn); mn = min(mn, s); } return ans; } };
方法二:動態規劃(Dynamic Programming)
類似地,我們可以固定右端點,定義 f(i) 為以 nums[i] 結尾的最大子陣列和。而在考慮第 i 個元素時,我們有兩種選擇:
classSolution: defmaxSubArray(self, nums: List[int]) -> int: n = len(nums) f = [-float('inf')] * (n + 1) for i, x inenumerate(nums): f[i + 1] = max(f[i] + x, x) returnmax(f)
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxSubArray(vector<int>& nums){ int n = nums.size(); vector<int> f(n + 1, -INT_MAX / 2); for (int i = 0; i < n; ++i) { f[i + 1] = max(f[i] + nums[i], nums[i]); } return *max_element(f.begin(), f.end()); } };
方法二優化:滾動陣列(Rolling Array)
在原本的方法二中,我們需要一個額外的陣列 f 來存儲所有的 f(i) 值,但實際上,我們只需要考慮前一個狀態 f(i−1) 即可。因此,我們可以可以用 滾動 的方式優化空間複雜度,使用一個變數 f 來記錄 f(i−1)。
但這樣我們會損失 f(i) 的資訊,因此我們需要動態地在更新 f 的同時更新最大值 ans。
複雜度分析
時間複雜度:O(n),其中 n 是陣列的長度。
空間複雜度:O(1)。
1 2 3 4 5 6 7 8
classSolution: defmaxSubArray(self, nums: List[int]) -> int: ans = -float('inf') f = 0 for x in nums: f = max(f + x, x) ans = max(ans, f) return ans
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxSubArray(vector<int>& nums){ int ans = INT_MIN, f = 0; for (int x : nums) { f = max(f + x, x); ans = max(ans, f); } return ans; } };
masterpiece, best quality, high quality, extremely detailed CG unity 8k wallpaper, extremely detailed, High Detail, vibrant colors, backlight, photo background,
1other, solo, no humans, Sylveon, Sylveon (Pokémon), Pokémon, blue eyes, full body, outdoors, sky, day, o, blue sky, grass, grassland, looking up,
A serene hand-drawn scene featuring Sylveon, a Pokémon with flowing ribbons, standing in a vibrant green meadow under a clear blue sky. Its eyes are blue, and its ears are a vibrant shade of pink, while its tail is a lighter shade of gray. The ribbons are gently swaying in the wind, and the art style is soft and painterly, emphasizing tranquility and freedom. Detailed grass in the foreground contrasts with the bright, open sky.