Leetcode 53. Maximum Subarray (Medium) (java)
2016-09-24 00:37
225 查看
Leetcode 53. Maximum Subarray (Medium) (java)
Tag: Array, Divide and Conquer, Dynamic Programming
Difficulty: Medium
/*
53. Maximum Subarray (Medium)
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*/
public class Solution {
public int maxSubArray(int[] nums) {
int _sum = Integer.MIN_VALUE, prev = 0;
for (int i = 0; i < nums.length; i++) {
prev = Math.max(prev + nums[i], nums[i]);
_sum = Math.max(_sum, prev);
}
return _sum;
}
};
Tag: Array, Divide and Conquer, Dynamic Programming
Difficulty: Medium
/*
53. Maximum Subarray (Medium)
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*/
public class Solution {
public int maxSubArray(int[] nums) {
int _sum = Integer.MIN_VALUE, prev = 0;
for (int i = 0; i < nums.length; i++) {
prev = Math.max(prev + nums[i], nums[i]);
_sum = Math.max(_sum, prev);
}
return _sum;
}
};
相关文章推荐
- [LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C++/Java/Python)
- [LeetCode] 011. Container With Most Water (Medium) (C++/Java/Python)
- Leetcode 31. Next Permutation (Medium) (java)
- Leetcode 39. Combination Sum (Medium) (java)
- Leetcode 48. Rotate Image (Medium) (java)
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- Leetcode 57. Insert Interval (Medium) (java)
- Leetcode 16. 3Sum Closest (Medium) (java)
- Leetcode 15. 3Sum (Medium) (java)
- Leetcode 54. Spiral Matrix (Medium) (java)
- [LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)
- [LeetCode] 022. Generate Parentheses (Medium) (C++/Java/Python)
- [LeetCode] 018. 4Sum (Medium) (C++/Java/Python)
- Leetcode 18. 4Sum (Medium) (java)
- [LeetCode]-319. Bulb Switcher (Medium)(Java)
- [LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)
- [LeetCode] 017. Letter Combinations of a Phone Number (Medium) (C++/Java/Python)
- Java for LeetCode 207 Course Schedule【Medium】
- Leetcode 179. Largest Number (Medium) (java)
- Leetcode 55. Jump Game (Medium) (java)