Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
[−2,1,−3,4,−1,2,1,−5,4]
,the contiguous subarray
[4,−1,2,1]
has the largest sum = 6
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int maxSubArray(vector<int>& nums) { | |
int maxSum=-INT_MAX; | |
int curSum=0; | |
int p=0; | |
while(p<=nums.size()-1){ | |
curSum=curSum+nums[p]; | |
curSum=curSum<0? nums[p]:curSum; | |
maxSum=curSum>maxSum? curSum:maxSum; | |
curSum=curSum>0? curSum:0; | |
p++; | |
} | |
return maxSum; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int maxSubArray(vector<int>& nums) { | |
int maxSum = INT_MIN, currentSum = 0; | |
for( int i = 0; i < nums.size(); ++i ){ | |
maxSum = max( maxSum, currentSum+= nums[i] ); | |
currentSum = ( currentSum < 0 ) ? 0 : currentSum; | |
} | |
return maxSum; | |
} | |
}; |
Round 2 solution:
This solution will take into account a case where all numbers are negative.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int maxSubArray(vector<int>& nums) { | |
if(nums.empty()) | |
return 0; | |
int maxSum=nums[0]; | |
int curSum=0; | |
for(int i=0; i<nums.size(); i++){ | |
curSum = curSum + nums[i]; | |
maxSum = max(curSum, maxSum); | |
curSum = curSum<0? 0:curSum; | |
} | |
return maxSum; | |
} | |
}; |
No comments:
Post a Comment