Maximum Product Subarray LT152

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Idea 1. How can we extend a solution from nums[0..i] to nums[0..i+1]? what shall we do for a newly added element nums[i+1]. Similar to Maximum Subarray LT53, assume we know the largest product for array nums[0..i],

    if nums[i+1] >= 0, maxProduct(i+1) = Math.max(maxProduct(i) * nums[i+1], nums[i+1])

    if nums[i+1] < 0, to get the max product ending at (i+1), we also need to know the min element ending at i which could be negative, maxProduct(i+1) = Math.max(minProduct(i) * nums[i+1], nums[i+1]).

    For any element at i+1, maxProduct(i+1) = Math.max( nums[i+1], minProduct(i) * nums[i+1], maxProduct(i) * nums[i+1] )

Time complexity: O(n)

Space complexity: O(1)

 1 class Solution {
 2     public int maxProduct(int[] nums) {
 3         int minHere = 1, maxHere = 1, result = Integer.MIN_VALUE;
 4         
 5         for(int num: nums) {     
 6             int res1 = minHere * num;
 7             int res2 = maxHere * num;
 8             if(res1 < res2) {
 9                 minHere = Math.min(res1, num);
10                 maxHere = Math.max(res2, num);
11             }
12             else {
13                 minHere = Math.min(res2, num);
14                 maxHere = Math.max(res1, num);
15             }
16             result = Math.max(result, maxHere);
17         }
18         return result;
19     }
20 }
 1 class Solution {
 2     public int maxProduct(int[] nums) {
 3         int minHere = 1, maxHere = 1, result = Integer.MIN_VALUE;
 4         
 5         for(int num: nums) {     
 6             int res1 = minHere * num;
 7             int res2 = maxHere * num;
 8             
 9             minHere = Math.min(Math.min(res1, res2), num);
10             maxHere = Math.max(Math.max(res1, res2), num);
11             
12             result = Math.max(result, maxHere);
13         }
14         return result;
15     }
16 }

posted on 2019-02-24 03:20  一直走在路上  阅读(123)  评论(0)    收藏  举报

导航