Last active
April 15, 2023 00:46
-
-
Save germanescobar/71f74680e59ea7e8c2fa1da3a4e0fd42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var maxProduct = function(nums) { | |
let max = -Infinity | |
const memo = {} | |
for (let i=0; i < nums.length; i++) { | |
const result = dp(nums, i, nums.length, memo) | |
if (result.max > max) { | |
max = result.max | |
} | |
} | |
return max | |
}; | |
function dp(nums, start, end, memo) { | |
if (end - start === 1) { | |
return { min: nums[start], max: nums[start] } | |
} | |
if (memo[`${start}-${end}`]) { | |
return memo[`${start}-${end}`] | |
} | |
const r = dp(nums, start + 1, end, memo) | |
const max = Math.max(nums[start], nums[start] * r.max, nums[start] * r.min) | |
const min = Math.min(nums[start], nums[start] * r.max, nums[start] * r.min) | |
const result = { max , min } | |
memo[`${start}-${end}`] = result | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment