码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Product Subarray LT152

时间:2019-02-24 10:25:23      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:Plan   result   log   style   xpl   sum   from   could   rom   

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 }

Maximum Product Subarray LT152

标签:Plan   result   log   style   xpl   sum   from   could   rom   

原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10425208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!