Leetcode: Maximum Product Subarray
LeetCode maximum product Subarray
2023-09-11 14:14:08 时间
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 Subarray很像,只是把加法换成了乘法,还是用一维动态规划中的“局部最优和全局最优法”。这里的区别是维护一个局部最优不足以求得后面的全局最优,这是由于乘法的性质不像加法那样,累加结果只要是正的一定是递增,乘法中有可能现在看起来小的一个负数,后面跟另一个负数相乘就会得到最大的乘积。不过事实上也没有麻烦很多,我们只需要在维护一个局部最大的同时,在维护一个局部最小,这样如果下一个元素遇到负数时,就有可能与这个最小相乘得到当前最大的乘积和,这也是利用乘法的性质得到的。
需要注意的是,在更新完max_local之后,去更新min_local, 需要用max_local, 要用更新之前的,而不是更新之后的
1 public class Solution { 2 public int maxProduct(int[] A) { 3 if (A==null || A.length==0) return 0; 4 int max_local = A[0]; 5 int min_local = A[0]; 6 int global = A[0]; 7 for (int i=1; i<A.length; i++) { 8 int max_copy = max_local; 9 max_local = Math.max(Math.max(max_local*A[i], A[i]), min_local*A[i]); 10 min_local = Math.min(Math.min(max_copy*A[i], A[i]), min_local*A[i]); 11 global = Math.max(max_local, global); 12 } 13 return global; 14 } 15 }
相关文章
- Leetcode: Maximum Size Subarray Sum Equals k
- Leetcode: Maximum Product of Word Lengths
- Leetcode: Bulls and Cows
- Leetcode: Maximum Depth of Binary Tree
- leetcode 二分法 Pow(x, n)
- JS leetcode 合并两个有序数组 解题分析
- [LeetCode] Merge Intervals
- [LeetCode]121. 买卖股票的最佳时机
- 【LeetCode】239. Sliding Window Maximum
- 【LeetCode】104. Maximum Depth of Binary Tree (2 solutions)
- 【leetcode 桶排序】Maximum Gap
- 【LeetCode】【Python题解】Reverse Integer
- [LeetCode] 1186. Maximum Subarray Sum with One Deletion 删除一次得到子数组最大和
- [LeetCode] 998. Maximum Binary Tree II 最大二叉树之二
- [LeetCode] 962. Maximum Width Ramp 最大宽度坡
- [LeetCode] Magic Squares In Grid 网格中的神奇正方形
- [LeetCode] 559. Maximum Depth of N-ary Tree N叉树的最大深度
- [LeetCode] 644. Maximum Average Subarray II 子数组的最大平均值之二
- [LeetCode] Flatten Nested List Iterator 压平嵌套链表迭代器
- [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变
- [LeetCode] 239. Sliding Window Maximum 滑动窗口最大值
- [LeetCode] 13. Roman to Integer 罗马数字转化成整数
- [LeetCode] 104. Maximum Depth of Binary Tree 二叉树的最大深度
- leetcode算法53.最大子数组和