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.
class Solution { public int maxProduct(int[] nums) { int l = nums.length; int max = nums[0]; int[] dp_min = new int[l]; int[] dp_max = new int[l]; dp_min[0] = dp_max[0] = max; for(int i = 1; i < l; i++){ dp_min[i] = Math.min( Math.min(nums[i], dp_min[i-1] * nums[i]), nums[i] * dp_max[i-1]); dp_max[i] = Math.max( Math.max(nums[i] * dp_min[i-1], nums[i] * dp_max[i-1]), nums[i]); max = Math.max(max, dp_max[i]); } return max; } }
转自 https://blog.csdn.net/whuwangyi/article/details/39577455
由于负数的存在,需要同时保存当前最大值和当前最小值,所以需要维护两个DP表,可以分别表示为dp_min和dp_max。所以即为dp_max里的最大值。
有时候做题目应该有一种大局观,从细节中解脱出来。这点类似于做物理题时,不一定非要用动力学原理弄清整个过程和每个细节,有时候用简单的从功和能的角度,只关注最终状态也可以顺利解题。这题里需要维护的当前最大值和当前最小值,都是在dp_min[i-1] * A[i],dp_max[i] * A[i],和A[i]这三者里面取一即可。有了这个只关乎最终状态,不关乎过程细节的结论,解题过程可以大大简化。
---------------------
作者:SciPioneer
来源:CSDN
原文:https://blog.csdn.net/whuwangyi/article/details/39577455
版权声明:本文为博主原创文章,转载请附上博文链接!