ποΈ Problems
Maximum Score from Performing Multiplication Operations - LeetCode
You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.
You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:
- Choose one integer x from either the start or the end of the array nums.
- Add `multipliers[i] * x` to your score.
- Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on.
- Remove x from nums.
Return the maximum score after performing m operations.
Input: nums = [1,2,3], multipliers = [3,2,1]
Output: 14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
- Choose from the end, [1], adding 1 * 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
π€ First attempt
- iλ²μ§Έμμ μΌμͺ½ νΉμ μ€λ₯Έμͺ½μ μ ννκ³ , μ΄ μ νμ λ°λΌμ λ―Έλμ μν₯μ λ―ΈμΉλ―λ‘ dynamic programming μ΄λΌ μκ°ν¨.
- greedy λΌλ©΄ νμ¬ ν° μͺ½λ§μ μ ννλ©΄ λκ² μ§λ§ νμ¬ μμ κ±° μ νν μ΄νμ μμ£Ό ν° κ°μ΄ μ¨μ΄ μμ μ μμΌλ―λ‘ greedy ν μ νμ΄ λ΅μ΄ λ μλ μμ.
β¨ Idea
- 0λ²μ§ΈλΆν° μΌμͺ½, μ€λ₯Έμͺ½ μ νμ recursive λ‘ κ³μ°
- μΌμͺ½ μ ν μ
nums[left] * multipliers[times] + dfs(left + 1, times + 1)
- μ€λ₯Έμͺ½ μ ν μ
nums[right] * multipliers[times] + dfs(left, times + 1)
- νμ¬ λ¨κ³μμλ recursive λ‘ κ³μ° μ΄ λ κ° μ€μμ ν° κ°μ return
- μΌμͺ½ μ ν μ
- μ΄λ₯Ό
multipliers[]
λκΉμ§ κ³μ°
π Intuition
μ΄ λ¬Έμ μμ κ°μ₯ μ΄λ €μ λ λΆλΆμ ν λ² μ νμ ν λ€μμ μ΄νμλ μ νλ κ°μ λ°°μ ν array μμ μ νμ ν΄μΌνλλ° μ΄ λΆλΆ μ²λ¦¬κ° μ΄λ €μ μ. μ νν κ°μ μ§μ΄ arrayλ₯Ό κ³μ κ°μ§κ³ κ°μΌ νλλ°... μ’μ λ°©λ²μ΄ μμμ΅λλ€.
λ€μ κ²½μ°μ right
index λ μλ κ³μ°μ΄ κ°λ₯ν κΉμ ?
- μ£Όμ΄μ§
nums
array μ length λN
. - νμ¬ μΌμͺ½ index κ°
left
- νμ¬ μ΄ μ ν νμ
times
π‘ [object Object] λ μλ κ³μ° κ°λ₯νκ° ?
λͺ¨λ κ²μ μ€λ₯Έμͺ½μμλ§ μ ννλ€λ©΄
right = N - 1 - times;
times
μ€μμ λͺ λ²μ left
μμ μ νμ νλ€λ©΄
- λ§€λ² μ€λ₯Έμͺ½μμλ§ μ ννλ€λ©΄
times
λ§νΌ μ€μ΄λ€ν λ° - κ·Έμ€μμ
left
λ§νΌμ μΌμͺ½μμ μ νμ νμΌλ―λ‘ μ€λ₯Έμͺ½μ κ·Έλ§νΌ μ€μ΄λ€μ§ μμλ λ¨.
right = N - 1 - (times - left);
πΈοΈβ¬οΈπ₯ top-down Solution
const N = nums.length;
const NM = multipliers.length;
const cache = {};
const genKey = (left, times) => `${left}:${times}`;
const dfs = (left, times) => {
const key = genKey(left, times);
if (times >= NM) return 0;
if (cache[key] !== undefined) return cache[key];
const right = N - 1 - (times - left);
const leftValue = nums[left] * multipliers[times] + dfs(left + 1, times + 1);
const rightValue = nums[right] * multipliers[times] + dfs(left, times + 1);
return (cache[key] = Math.max(leftValue, rightValue));
};
return dfs(0, 0);