1
\$\begingroup\$

I have come up with the following solution to find the maximum product for a contiguous sub-array:

def maxProduct(nums):
 
 max_prod = [0]*len(nums)
 min_prod = [0]*len(nums)
 for i in range(0, len(nums)):
 min_prod[i] = min(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i])
 max_prod[i] = max(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i])
 
 
 return max(max_prod)

Current solution is O(n) in space, trying to find O(1) solution for space, but I keep seem to missing it. Ideas?

Mast
13.8k12 gold badges56 silver badges127 bronze badges
asked Jul 19, 2020 at 7:19
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  1. Follow PEP8 style guide for variable and function naming convention. Both the variables and function names should have snake_case names.
  2. You can use enumerate to get index and value while iterating a list.

For constant space solution, instead of using a list to keep track of current max and min products, use a variable for both positive product and negative product. If the current number is \$ 0 \$, reset them both to \$ 1 \$ (They should be initialised as \$ 1 \$ as well). At the end of for-loop (inside the loop), keep updating your current_max value to keep track of max product encountered so far.


As edge cases, you may also consider returning (or raising errors) when input was empty etc.

answered Jul 19, 2020 at 8:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.