|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def maxProduct(self, nums: List[int]) -> int: |
| 6 | + """ |
| 7 | + 状态压缩 |
| 8 | + """ |
| 9 | + if len(nums) < 1: |
| 10 | + raise KeyError |
| 11 | + maxs = dp_maxs = dp_mins = nums[0] |
| 12 | + for i in range(1, len(nums)): |
| 13 | + pre_dp_maxs = dp_maxs |
| 14 | + dp_maxs = max(dp_maxs * nums[i], dp_mins * nums[i], nums[i]) |
| 15 | + # notes, 使用上次的 dp_maxs, 而非刚计算出来的 |
| 16 | + dp_mins = min(pre_dp_maxs * nums[i], dp_mins * nums[i], nums[i]) |
| 17 | + maxs = max(maxs, dp_maxs) |
| 18 | + return maxs |
| 19 | + |
| 20 | + |
| 21 | +# class Solution: |
| 22 | +# def maxProduct(self, nums: List[int]) -> int: |
| 23 | +# """ |
| 24 | + |
| 25 | +# -2 (-2) |
| 26 | +# 3 (3, -6) |
| 27 | +# 2 (2, 6, -12) |
| 28 | +# -1 (-1, -2, -6, 12) |
| 29 | +# 7 (7, -7, -14, -42, 84) |
| 30 | +# => 84 |
| 31 | +# 如何求最大乘积, 正*正,负*负 |
| 32 | +# max min |
| 33 | +# -2 (,,2) -2 (-2) -2 (-2) |
| 34 | +# 3 (-6,-6,3) 3 (3) -6 (-2,3) |
| 35 | +# 2 (6,-12,2) 6 (3,2) -12(-2,3,2) |
| 36 | +# -1 (-6,12,-1) 12 (-2,3,2,-1) -6 (3,2,-1) |
| 37 | +# 7 (84,-42,7) 84 (-2,3,2,-1,7) -42(3,2,-1,7) |
| 38 | +# => 84 |
| 39 | +# dp_maxs[i]: 到数据i所构成连续子数据的最大乘积 |
| 40 | +# dp_mins[i]: 到数据i所构成连续子数据的最小乘积 |
| 41 | +# dp_maxs[i] = max(dp_maxs[i-1]*nums[i], dp_mins[i-1]*nums[i], nums[i]) |
| 42 | +# dp_mins[i] = min(dp_maxs[i-1]*nums[i], dp_mins[i-1]*nums[i], nums[i]) |
| 43 | +# max(dp_maxs) |
| 44 | +# """ |
| 45 | +# if len(nums) < 1: |
| 46 | +# raise KeyError |
| 47 | +# dp_maxs = [0 for _ in nums] |
| 48 | +# dp_mins = [0 for _ in nums] |
| 49 | +# dp_maxs[0] = dp_mins[0] = nums[0] |
| 50 | +# for i in range(1, len(nums)): |
| 51 | +# dp_maxs[i] = max(dp_maxs[i - 1] * nums[i], dp_mins[i - 1] * nums[i], nums[i]) |
| 52 | +# dp_mins[i] = min(dp_maxs[i - 1] * nums[i], dp_mins[i - 1] * nums[i], nums[i]) |
| 53 | +# return max(dp_maxs) |
| 54 | + |
| 55 | + |
| 56 | +# class Solution: |
| 57 | +# def maxProduct(self, nums: List[int]) -> int: |
| 58 | +# """ |
| 59 | +# -2 (-2) |
| 60 | +# 3 (3, -6) |
| 61 | +# 2 (2, 6, -12) |
| 62 | +# -1 (-1, -2, -6, 12) |
| 63 | +# 7 (7, -7, -14, -42, 84) |
| 64 | +# => 84 |
| 65 | +# """ |
| 66 | +# if len(nums) < 1: |
| 67 | +# raise KeyError |
| 68 | +# maxs = nums[0] |
| 69 | +# starts = set([nums[0]]) |
| 70 | +# for num in nums[1:]: |
| 71 | +# next_starts = set([num]) |
| 72 | +# for start in starts: |
| 73 | +# next_starts.add(num * start) |
| 74 | +# maxs = max(*next_starts, maxs) |
| 75 | +# starts = next_starts |
| 76 | +# return maxs |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + assert Solution().maxProduct(nums=[2, 3, -2, 4]) == 6 |
| 81 | + assert Solution().maxProduct(nums=[-2, 0, -1]) == 0 |
| 82 | + assert Solution().maxProduct(nums=[-2, 3, 2, -1, 7]) == 84 |
| 83 | + assert Solution().maxProduct(nums=[-3, -4, -2]) == 12 |
0 commit comments