LeetCode刷題筆記(貪心):maximum-subarray
題目描述
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
在一個數組中找到連續的子陣列(至少包含一個數字),這個陣列的總和最大。 例如,給定陣列[-2,1,-3,4,-1,2,1,-5,4],連續的子陣列[4,-1,2,1]具有最大的和= 6。 更多的練習:如果你已經找到了O(n)的解決方案,嘗試使用分而治之的方法編碼另一個解決方案,這是更微妙的。
解題思路
從頭開始累加,直到和為負。此時前面這段不能給後面的串帶來正收益,應捨棄,sum清零,然後再開始統計最大的sum。演算法時間複雜度O(n)。
題目中說可以嘗試一下分治法,我是沒想出來,後來看了leetcode上大神的程式碼才恍然大悟知道要怎麼寫。
For each subarray, calculate four attributes:
mx (largest sum of this subarray),
lmx(largest sum starting from the left most element),
rmx(largest sum ending with the right most element),
sum(the sum of the total subarray).
演算法複雜度作者竟然說是O(n),但是我覺得是O(logn)?
class Solution {
public:
void maxSubArray(vector<int>& nums, int l, int r, int& mx, int& lmx, int& rmx, int& sum) {
if (l == r) {
mx = lmx = rmx = sum = nums[l];
}
else {
int m = (l + r) / 2;
int mx1, lmx1, rmx1, sum1;
int mx2, lmx2, rmx2, sum2;
maxSubArray(nums, l, m, mx1, lmx1, rmx1, sum1);
maxSubArray(nums, m + 1, r, mx2, lmx2, rmx2, sum2);
mx = max(max(mx1, mx2), rmx1 + lmx2);
lmx = max(lmx1, sum1 + lmx2);
rmx = max(rmx2, sum2 + rmx1);
sum = sum1 + sum2;
}
}
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) {
return 0;
}
int mx, lmx, rmx, sum;
maxSubArray(nums, 0, nums.size() - 1, mx, lmx, rmx, sum);
return mx;
}
};
C++版程式碼實現
class Solution {
public:
int maxSubArray(int A[], int n) {
if(A == NULL || n == 0)
return false;
int sum = A[0];
int maxSum = A[0];
for(int i = 1; i < n; ++i){
if(sum < 0)
sum = 0;
sum += A[i];
maxSum = max(sum, maxSum);
}
return maxSum;
}
};
系列教程持續釋出中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz