Today I have solved the problem in javascript
Write a program that determines the smallest number of perfect squares that sum up to N.
Here are a few examples:
Given N = 4, return 1 (4)
Given N = 17, return 2 (16 + 1)
Given N = 18, return 2 (9 + 9)
function numSquares(N) {
const dp = new Array(N + 1).fill(Infinity);
dp[0] = 0;
for (let i = 1; i <= N; i++) {
for (let j = 1; j * j <= i; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}return dp[N];
}
console.log(numSquares(4));
console.log(numSquares(17));
console.log(numSquares(18));
Output:
1 2 2
Comments
Post a Comment