-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0343-integer-break.js
More file actions
32 lines (26 loc) · 1.11 KB
/
0343-integer-break.js
File metadata and controls
32 lines (26 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Integer Break
* Time Complexity: O(n^2)
* Space Complexity: O(n)
*/
var integerBreak = function (n) {
if (n <= 3) {
return n - 1;
}
const maxProductValues = new Array(n + 1).fill(0);
maxProductValues[2] = 1;
maxProductValues[3] = 2;
for (let currentNumber = 4; currentNumber <= n; currentNumber++) {
let currentMaxAchieved = 0;
for (let firstPartValue = 1; firstPartValue <= Math.floor(currentNumber / 2); firstPartValue++) {
let secondPartValue = currentNumber - firstPartValue;
let productOption1 = firstPartValue * secondPartValue;
let productOption2 = firstPartValue * maxProductValues[secondPartValue];
let productOption3 = maxProductValues[firstPartValue] * secondPartValue;
let productOption4 = maxProductValues[firstPartValue] * maxProductValues[secondPartValue];
currentMaxAchieved = Math.max(currentMaxAchieved, productOption1, productOption2, productOption3, productOption4);
}
maxProductValues[currentNumber] = currentMaxAchieved;
}
return maxProductValues[n];
};