[LeetCode]53. Maximum Subarray
2017-07-29 08:26
302 查看
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
public class Solution {
public int maxSubArray(int[] nums) {
int MaxSoFar = Integer.MIN_VALUE;
int MaxEndingHere = 0;
for(int i=0; i<nums.length; i++){
if(MaxEndingHere<0)
MaxEndingHere=0;
MaxEndingHere+=nums[i];
MaxSoFar = Math.max(MaxEndingHere,MaxSoFar);
}
return MaxSoFar;
}
}
Dynamic Programming
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.
public class Solution {
public int maxSubArray(int[] nums) {
int MaxSoFar = Integer.MIN_VALUE;
int MaxEndingHere = 0;
for(int i=0; i<nums.length; i++){
if(MaxEndingHere<0)
MaxEndingHere=0;
MaxEndingHere+=nums[i];
MaxSoFar = Math.max(MaxEndingHere,MaxSoFar);
}
return MaxSoFar;
}
}
Dynamic Programming
相关文章推荐
- leetcode: 53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- [leetcode]: 53. Maximum Subarray
- LeetCode53. Maximum Subarray
- 【LeetCode】53. Maximum Subarray
- [LeetCode]53. Maximum Subarray
- leetcode-53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- [Leetcode] 53. Maximum Subarray
- Leetcode:53. Maximum Subarray
- LeetCode - 53. Maximum Subarray
- leetcode-53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- leetcode -- 53. Maximum Subarray
- LeetCode *** 53. Maximum Subarray
- Leetcode题解 - 53. Maximum Subarray
- leetcode_53. Maximum Subarray-子数组最大和
- LeetCode 53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- Leetcode 53. Maximum Subarray