**53.最大子序和

給定一個整數數組 nums ,找到一個具有最大和的連續子數組(子數組最少包含一個元素),返回其最大和。

示例:

輸入: [-2,1,-3,4,-1,2,1,-5,4],
輸出: 6
解釋: 連續子數組 [4,-1,2,1] 的和最大,爲 6。
進階:

如果你已經實現複雜度爲 O(n) 的解法,嘗試使用更爲精妙的分治法求解。

思路:

  • 動態規劃
  • res [ i ] 以 num [ i ] 結尾的 最大子序和
public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) {
      return 0;
    }
    int[] res = new int[nums.length]; // 以 i 結尾的最大子序和
    res[0] = nums[0];
    int max = nums[0];

    for (int i = 1; i < nums.length; i++) {
      int curMax = nums[i] + res[i - 1];
      if (curMax > nums[i]) {
        res[i] = curMax;
      } else {
        res[i] = nums[i];
      }
      max = Math.max(max, res[i]);
    }
    return max;
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章