Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题意
求连续子集的最大和
题解
其实我觉得这题挺难的|||
首先是O(n)解法
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int e = 1, n = nums.size(), ans = nums[0], now = nums[0]; 5 while (e < n) { 6 now = max(now + nums[e], nums[e]); 7 ans = max(now, ans); 8 e++; 9 } 10 return ans; 11 } 12 };
然后是分治算法
1 class Solution { 2 public: 3 int maxSubRange(vector<int>&nums, int x, int y) { 4 if (x == y)return nums[x]; 5 int mid = (x + y) / 2; 6 int lmax = maxSubRange(nums, x, mid), rmax = maxSubRange(nums, mid + 1, y); 7 int tmp = 0, mmax = 0; 8 for (int i = mid - 1; i >= x; i--) { 9 tmp += nums[i]; 10 mmax = max(tmp, mmax); 11 } 12 tmp = mmax; 13 for (int i = mid; i <= y; i++) { 14 tmp += nums[i]; 15 mmax = max(tmp, mmax); 16 } 17 return max(mmax, max(lmax, rmax)); 18 } 19 int maxSubArray(vector<int>& nums) { 20 int e = 1, n = nums.size(), ans = nums[0], now = nums[0]; 21 while (e < n) { 22 now = max(now + nums[e], nums[e]); 23 ans = max(now, ans); 24 e++; 25 } 26 return ans; 27 } 28 };