LeetCode题解(0152):乘积最大子数组(Python)
发布日期:2021-06-29 20:16:02 浏览次数:2 分类:技术文章

本文共 797 字,大约阅读时间需要 2 分钟。

题目:(中等)

标签:贪心算法、数组、动态规划

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1) 60ms (17.95%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:    def maxProduct(self, nums: List[int]) -> int:        ans = float("-inf")        last1 = 0  # 绝对值最大的正数        last2 = 0  # 绝对值最大的负数        for num in nums:            if num == 0:                last1, last2 = 0, 0                ans = max(ans, 0)            elif num > 0:                last1, last2 = ((last1 * num) if last1 != 0 else num), ((last2 * num) if last2 != 0 else 0)                ans = max(ans, last1)            else:                last1, last2 = ((last2 * num) if last2 != 0 else 0), ((last1 * num) if last1 != 0 else num)                ans = max(ans, last2, last1 if last1 != 0 else float("-inf"))        return ans

转载地址:https://dataartist.blog.csdn.net/article/details/112607286 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(0162):寻找峰值(Python)
下一篇:LeetCode题解(LCP15):游乐园的迷宫(Python)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月28日 23时20分03秒