首页 > 其他 > 详细

Leetcode #152 Maximum Product Subarray

时间:2015-04-05 23:19:41      阅读:285      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!