Monday, June 16, 2014

Leetcode - 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.
[Thoughts]: 动态规划, sum代表的以i位置作为结束点的子序列的最大和。
public class Solution {
    public int maxSubArray(int[] A) {
        int sum = A[0], max = A[0];
        for(int i = 1; i<A.length; i++){
            sum = Math.max(sum+A[i], A[i]);
            max = Math.max(sum, max);
        }
        return max;
    }
}
最大积序列。res代表以i位置作为结束点的子序列的最大积,min为最小积。
public double maxProduct(double[] arr){
    double max = 1;
    double min = 1;
    double res = 1;
    for(int i=0; i<arr.length; i++){
        double restemp = Math.max(res*arr[i], Math.max(arr[i], min*arr[i]));
        double mintemp = Math.min(res*arr[i], Math.min(arr[i], min*arr[i]));
        res = restemp;
        min = mintemp;
       
        max = Math.max(res, max);
    }
    return max;
}

No comments:

Post a Comment