53. 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
.
连续子数组的最大和
C++(9ms):
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int len = nums.size() ; 5 if (len < 1) 6 return 0 ; 7 int sum = 0 ; 8 int Max = nums[0] ; 9 for (int i = 0 ; i < len ; i++){ 10 if (sum < 0) 11 sum = nums[i] ; 12 else 13 sum += nums[i] ; 14 if (sum > Max) 15 Max = sum ; 16 } 17 return Max ; 18 } 19 };
java(15ms):
1 class Solution { 2 public int maxSubArray(int[] nums) { 3 if (nums.length < 1) 4 return 0 ; 5 int Max = nums[0] ; 6 int sum = 0 ; 7 for(int i = 0 ; i < nums.length ; i++){ 8 if (sum < 0){ 9 sum = nums[i] ; 10 }else{ 11 sum += nums[i] ; 12 } 13 if (sum > Max) 14 Max = sum ; 15 } 16 return Max ; 17 } 18 }