leetcode Maximum Subarray

来源:互联网 发布:友情岁月演唱会知乎 编辑:程序博客网 时间:2024/04/28 17:40

Maximum Subarray 原题地址:

https://oj.leetcode.com/problems/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.

这道题的解法在编程之美上有。大致描述就是0...j中的最大子序列之和等于0...j-1的最大子序列之和与包括j的最大子序列之和的最大值。

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


0 0
原创粉丝点击