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

Leetcode #152 Maximum Product Subarray

时间:2015-04-05 23:22:57      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/maximum-product-subarray/

较麻烦的解法:

  • 先判断数组中有没有0,有的话可以转换为求"0之前"和"0之后"两部分的较大值。

  • 遍历,记录数组中负数的个数:  

    • 偶数:由于数组中都是整数,最大值即这些值的乘积。

    • 奇数:有以下几种可能,取它们中的最大值。

      • 第一个负数 / 最后一个负数。

      • 第一个负数之前的乘积 / 最后一个负数之前的乘积。

      • 第一个负数之后的乘积 / 最后一个负数之后的乘积。

 

官方 Solution 给出的解法:

Besides keeping track of the largest product, we also need to keep track of the smallest product. Why? The smallest product, which is the largest in the negative sense could become the maximum when being multiplied by a negative number.

Let us denote that:

           f(k) = Largest product subarray, from index 0 up to k. 

Similarly, 

           g(k) = Smallest product subarray, from index 0 up to k.

Then,

f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )

g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )

  

There we have a dynamic programming formula. Using two arrays of size n, we could deduce the final answer as f(n-1). Since we only need to access its previous elements at each step, two variables are sufficient.

Leetcode #152 Maximum Product Subarray

标签:

原文地址:http://www.cnblogs.com/meowcherry/p/4394888.html

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