53. Maximum Subarray && 152. Maximum Product Subarray

53. 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.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 
DP Solution:
public class Solution {
    public int maxSubArray(int[] nums) {
        int temp = nums[0];
        int max = nums[0];
        for(int i = 1; i<nums.length; ++i)
        {
            if(temp>0 && temp+nums[i]>0)
                temp += nums[i];
            else
                temp = nums[i];
            max = Math.max(temp, max);
        }
        return max;
    }
}

 

152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

 
public class Solution {
  public int maxProduct(int[] nums) {
    int lastMax = nums[0];
    int lastMin = nums[0];
    int globalMax = nums[0];
    for (int i = 1; i < nums.length; ++i) {
      int cur = nums[i];
      int curMax = cur*lastMax;
      int curMin = cur*lastMin;
      lastMax = Math.max(cur, Math.max(curMax, curMin));
      lastMin = Math.min(cur, Math.min(curMax, curMin));
      globalMax = Math.max(lastMax, globalMax);
    }
    return globalMax;
  }
}

 

 
posted @ 2016-07-07 12:16  新一代的天皇巨星  阅读(136)  评论(0)    收藏  举报