Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Last active April 15, 2023 00:46
Show Gist options
  • Save germanescobar/71f74680e59ea7e8c2fa1da3a4e0fd42 to your computer and use it in GitHub Desktop.
Save germanescobar/71f74680e59ea7e8c2fa1da3a4e0fd42 to your computer and use it in GitHub Desktop.
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