|
| 1 | +/** |
| 2 | + * @param {number[]} nums |
| 3 | + * @param {number} k |
| 4 | + * @param {number} limit |
| 5 | + * @return {number} |
| 6 | + */ |
| 7 | +var maxProduct = function(nums, k, limit) { |
| 8 | + const MIN = -5000; |
| 9 | + const dp = new Map(); |
| 10 | + const n = nums.length; |
| 11 | + |
| 12 | + let sum = 0; |
| 13 | + for (const x of nums) sum += x; |
| 14 | + |
| 15 | + if (k > sum || k < -sum) return -1; |
| 16 | + |
| 17 | + |
| 18 | + const ans = recursion(0, 0, 0, 0, k, n, nums, limit); |
| 19 | + return (ans === MIN) ? -1 : ans; |
| 20 | + function recursion(pos, currSum, product, isOdd, k, n, nums, limit) { |
| 21 | + if (pos === n) { |
| 22 | + return (currSum === k && isOdd !== 0 && product <= limit ? product : MIN); |
| 23 | + } |
| 24 | + |
| 25 | + if (dp.has(pos) && dp.get(pos).has(currSum) && dp.get(pos).get(currSum).has(product) && dp.get(pos).get(currSum).get(product).has(isOdd)) { |
| 26 | + return dp.get(pos).get(currSum).get(product).get(isOdd); |
| 27 | + } |
| 28 | + |
| 29 | + let ans = recursion(pos + 1, currSum, product, isOdd, k, n, nums, limit); |
| 30 | + if (isOdd === 0) { |
| 31 | + ans = Math.max(ans, recursion(pos + 1, currSum + nums[pos], nums[pos], 2, k, n, nums, limit)); |
| 32 | + } |
| 33 | + if (isOdd === 1) { |
| 34 | + ans = Math.max(ans, recursion(pos + 1, currSum + nums[pos], Math.min(product * nums[pos], limit + 1), 2, k, n, nums, limit)); |
| 35 | + } |
| 36 | + if (isOdd === 2) { |
| 37 | + ans = Math.max(ans, recursion(pos + 1, currSum - nums[pos], Math.min(product * nums[pos], limit + 1), 1, k, n, nums, limit)); |
| 38 | + } |
| 39 | + |
| 40 | + if (!dp.has(pos)) { |
| 41 | + dp.set(pos, new Map()); |
| 42 | + } |
| 43 | + if (!dp.get(pos).has(currSum)) { |
| 44 | + dp.get(pos).set(currSum, new Map()); |
| 45 | + } |
| 46 | + if (!dp.get(pos).get(currSum).has(product)) { |
| 47 | + dp.get(pos).get(currSum).set(product, new Map()); |
| 48 | + } |
| 49 | + dp.get(pos).get(currSum).get(product).set(isOdd, ans); |
| 50 | + |
| 51 | + return ans; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | + |
| 56 | + |
0 commit comments