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.


思想就是用greedy algorithm,

1. 遍历数组,每一步取得最优值,比较看当前的值和包含当前值的最大字串哪个比较大。如果是当前的值比较大,那么相当于更新了当前找到的最大字串的起始位置。

2. 每一步再比较当前拿到的最大值和全局最大值,如果需要,更新全局的最大值。


public class Solution {
    public int maxSubArray(int[] A) {
        int result = Integer.MIN_VALUE;
        int current = 0;
        for(int i=0;i<A.length;i++){
            current = max(current+A[i],A[i]);
            result = max(result,current);
        }
        return result;
    }
        
    public int max(int a,int b){
        return a>b?a:b;
    }
}

你可能感兴趣的:(java,LeetCode,maximum,Subarray)