Leetcode之Maximum Product Subarray 问题

来源:互联网 发布:网络tv电视直播软件 编辑:程序博客网 时间:2024/06/02 17:16

问题描述:

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.

问题来源:Maximum Product Subarray (详细地址:https://leetcode.com/problems/maximum-product-subarray/description/)

思路分析:乘和加不一样的地方在于:乘可以一下变成最大,也可以一下子变得最小,因为有负数的存在,所以得考虑正负得负,负负得正。所以需要两个变量min和max,分别存储最小值和最大值,最小值期待着农奴翻身的一天,所以我们得帮他记录下来。另外,碰到小于0的数的时候,我们要将最小值和最大值交换掉,因为乘上这个小数之后,最大值和最小值要交换了,所以我们先交换好再乘。另外,最大值和最小值都有可能是当前元素本身,所以取的当前元素和乘积之后的结果比较后的结果。

代码:








原创粉丝点击