题目概述
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
1 | Input: [2,3,-2,4] |
Example 2:
1 | Input: [-2,0,-1] |
本题和之前求连续子序列的最大和的那题很像。但是乘法与加法不同,还需要考虑两个负数的乘积很大的情况。
在这里,我用的解法是动态规划。对于序列nums,为了求解出最大的连续子序列的最大乘积,需要维护三个数组,分别为max_local, min_local和max_global。max_local[i]的含义是,以索引为i结束的连续子序列的乘积最大值;min_local[i]的含义是,以索引为i结束的连续子序列的乘积最小值,max_global[i]为到索引i为止,全局的乘积最大值。其中max_local[0], min_local[0]以及max_global[0]都为nums[0]。动态规划的状态转移公式为:
1 | max_local[i] = max(max_local[i-1]*nums[i], min_local[i-1]*nums[i], nums[i]) |
代码实现
1 | class Solution: |