算法: 最大乘积子数组152. Maximum Product Subarray
Posted AI架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 最大乘积子数组152. Maximum Product Subarray相关的知识,希望对你有一定的参考价值。
152. Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
1. 左右两个方向,计算乘积,如果遇到0,则乘以1。java解法
public int maxProduct(int[] A)
int n = A.length, res = A[0], l = 0, r = 0;
for (int i = 0; i < n; i++)
l = (l == 0 ? 1 : l) * A[i];
r = (r == 0 ? 1 : r) * A[n - 1 - i];
res = Math.max(res, Math.max(l, r));
return res;
2. python解法,直接翻转数组
class Solution:
def maxProduct(self, nums: List[int]) -> int:
B = nums[::-1]
for i in range(1, len(nums)):
if nums[i-1] != 0: nums[i] *= nums[i-1]
if B[i-1] != 0: B[i] *= B[i-1]
return max(nums + B)
更加简洁的实现
class Solution:
def maxProduct(self, nums: List[int]) -> int:
B = nums[::-1]
for i in range(1, len(nums)):
nums[i] *= nums[i-1] or 1
B[i] *= B[i-1] or 1
return max(nums + B)
解释 A[i] *= A[i - 1] or 1
它就像这样(5 or 1)= 5
逻辑加法,如果是(x or 1)= x
一直如此,除非 x 为零,那么它是 1
参考
https://leetcode.com/problems/maximum-product-subarray/discuss/183483/JavaC%2B%2BPython-it-can-be-more-simple
以上是关于算法: 最大乘积子数组152. Maximum Product Subarray的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode]152. Maximum Product Subarray最大乘积子数组
[LeetCode] 152. Maximum Product Subarray 求最大子数组乘积