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.

最大连续子序列。最大可以是当前数或是当前数加上之前的数。

public class Solution {
  public int maxSubArray(int[] nums) {
    int tmp = nums[0];
    int max = tmp;
    for (int i = 1; i < nums.length; i++) {
      tmp = Math.max(tmp + nums[i], nums[i]);
      max = Math.max(tmp, max);
    }
  return max;
  }
}

posted on 2015-06-25 09:08  shini  阅读(86)  评论(0编辑  收藏  举报

导航