leetcode -- 53. Maximum Subarray

来源:互联网 发布:js 严格模式 编辑:程序博客网 时间:2024/06/05 12:05

题目

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.

题意

找出数组中连续子数组(至少包含一个数字)和最大,获得这个和。

代码及分析

  • 递推关系】前 i 个元素,或者与前 i-1个元素中部分相关,或者 只与第 i 个元素有关。(第i个元素一定要作为组成部分,否则不符合连续的要求)
  • 判断条件】前 i-1 个元素的如果小于0,那么对第 i 个元素有降低的作用。
  • 递推公式maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
  • 参考DP solution & some thoughts

public int maxSubArray(int[] A) {        int n = A.length;        int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];        dp[0] = A[0];        int max = dp[0];                for(int i = 1; i < n; i++){            dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);            max = Math.max(max, dp[i]);        }                return max;}


0 0