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.
Solutions
My solution
classSolution {public:intmaxSubArray(vector<int>& nums) {int max_sum = INT_MIN; // maximum subarray sumint sum =0;int min_sum =0; // minimum sum of first k elementsfor(int i =0; i <nums.size(); ++i){ sum +=nums[i]; max_sum =max(max_sum, sum - min_sum); min_sum =min(min_sum, sum); }return max_sum; }};
A slightly more efficient solution
classSolution {public:intmaxSubArray(vector<int>& nums) {int ans = INT_MIN;int max_sum =0; // maximum sum of subarray ending with the previous element;for(int i =0; i <nums.size(); ++i){ // need to consider too cases to update max_sum // case 1: without the previous element, i.e., use only the current element: // max_sum = nums[i] // case 2: with the previous element: // max_sum = nums[i] + max_sum max_sum =max(nums[i],nums[i] + max_sum); ans =max(ans, max_sum); }return ans; }};