題目
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
思路解析
就我的個人理解,這是一道即可看似動態規劃,又可看似貪心問題的題目。
在遍歷的每次迭代中,我們維護兩個變量,一個是全局最優global,就是到當前元素爲止最優的解,一個是局部最優local,就是必須包含當前元素的最優的解。
(1)對於local,如果加上當前值後,變成了負數,說明了2個事實:
i:當前值是負數
ii:此時的local已經沒有價值了,如果後續的連續子序列還包含目前這個子序列,那麼肯定不如不包含當前這個子序列的sum大
所以這時候直接把local重置爲0,連續子序列重新開始生成。
(2)對於global,每次迭代都與當前local比較,然後取二者中的最大值
整個過程只需要遍歷完一次原數組,所以時間複雜度是O(n)
C++實現
// Runtime: 9 ms
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (0 == nums.size()) return 0;
int global = nums[0], local = 0;
for (int i = 0; i < nums.size(); ++i){
local += nums[i];
global = max(local, global);
local = max(0, local);
}
return global;
}
};
Python實現
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
:Runtime: 42 ms
"""
if 0 == len(nums):
return 0
global_sum = nums[0]
local_sum = 0
for i in nums:
local_sum += i
global_sum = max(local_sum, global_sum)
local_sum = max(0, local_sum)
return global_sum