优化题目:LeetCode--53. Maximum Subarray
本题也是我们熟知的最大子序列和,题目如下:
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.
可能大家都已经知道最优解了,并且程序还特别的漂亮,比如我个人是比较喜欢这一版的:
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length < 1) {
return 0;
}
int res = Integer.MIN_VALUE;
int sum = 0;
for(int num : nums) {
sum += num;
res = Math.max(res, sum);
sum = Math.max(0, sum);