[LeetCode] 152. Maximum Product SubarrayeetCode] 152. Maximum Product Subarray(積最大的子陣列)
阿新 • • 發佈:2020-12-12
-
Difficulty: Medium
-
Related Topics: Array, Dynamic Programming
-
Link: https://leetcode.com/problems/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 } }