close

今天要來解的題目是 Leetcode-152. Maximum Product Subarray,難度為 Medium,

而我所使用的語言是 python3

壹、理解題目

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

Note: A subarray is a contiguous subsequence of the array.

也就是要找到一個 subarray 其所有數字相乘可以得到最大的數字,不須回傳 subarray,只要找到那個最大值就好!

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

貳、類似概念

和「Maximum Subarray / 最大和問題」(相加)很類似,可以先點這裡看那題的解析喔!

參、解題

和 Maximum Subarray 一樣,同樣會用到 Kadane's Algorithm,

但在這題中,我們還要同時記錄下 local_min,

因為 array 中有可能有負數,這樣乘了之後最大值就變最小值了,

你可能會說,喔那就不要乘阿,但有可能「最小值乘下去比原本的最大值還要大」!

另外,遇到負數的時候,local_max & local_min 的結果就得交換了,所以需要先做 swap。

image

image

arrow
arrow
    創作者介紹
    創作者 Sofie 舒霏 的頭像
    Sofie 舒霏

    Sofie 舒霏的部落格

    Sofie 舒霏 發表在 痞客邦 留言(0) 人氣()