Loading

[LeetCode] 152. Maximum Product SubarrayeetCode] 152. Maximum Product Subarray(积最大的子数组)

Description

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
给定一个整数数组 nums,找到积最大的子数组(至少包含一个整数)。

Examples

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.

Solution

这题看上去和最大子数组类似,只是把和最大变成了积最大。但是做法就发生了变化,由于无论怎么乘,结果的绝对值都是递增的(当然,0 的情况需要单独讨论)。所以,只要算一遍前缀和,一遍后缀和,就能得到结果。代码如下:

class Solution {
    fun maxProduct(nums: IntArray): Int {
        var result = nums[0]
        var left = 0
        var right = 0

        for (i in nums.indices) {
            left = (if (left == 0) 1 else left) * nums[i]
            right = (if (right == 0) 1 else right) * nums[nums.lastIndex - i]

            result = maxOf(result, left, right)
        }

        return result
    }
}
posted @ 2020-12-12 15:16  Zhongju.copy()  阅读(70)  评论(0编辑  收藏  举报