Advertisement
Rick10101221

Untitled

Oct 22nd, 2022
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. # https://leetcode.com/problems/maximum-product-subarray/solution/
  2. # Find start and ending indicies of maximum product subarray
  3.  
  4. class Solution:
  5.     def maxProduct(self, nums: List[int]) -> int:
  6.         if len(nums) == 0:
  7.             return 0
  8.  
  9.         max_so_far = nums[0]
  10.         min_so_far = nums[0]
  11.         result = max_so_far
  12.         end_index = 0
  13.         for i in range(1, len(nums)):
  14.             curr = nums[i]
  15.             temp_max = max(curr, max_so_far * curr, min_so_far * curr)
  16.             min_so_far = min(curr, max_so_far * curr, min_so_far * curr)
  17.  
  18.             max_so_far = temp_max
  19.             if max_so_far>result:
  20.                 result = max_so_far
  21.                 end_index = i
  22.      
  23.         cur = nums[end_index]
  24.         j = end_index-1
  25.         # no change in complexity
  26.         while cur != result and j>=0:
  27.             cur *= nums[j]
  28.             j -= 1
  29.         print(nums[j+1:i+1])
  30.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement