Skip to content

Commit c935eb5

Browse files
committed
Implement integer-break
name: integer-break url: https://leetcode.com/problems/integer-break difficulty: 2 time: 0 ms time-rank: 100.0 % time-complexity: O(N) space: 6.5 MB space-rank: 35.36 % space-complexity: O(N) Fixes #313 Signed-off-by: Christopher Friedt <[email protected]>
1 parent ab5ff32 commit c935eb5

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

integer-break-test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
#include <gtest/gtest.h>
8+
9+
#include "integer-break.cpp"
10+
11+
using namespace std;
12+
13+
TEST(IntegerBreak, 1) { EXPECT_EQ(1, Solution().integerBreak(1)); }
14+
15+
TEST(IntegerBreak, 2) { EXPECT_EQ(1, Solution().integerBreak(2)); }
16+
17+
TEST(IntegerBreak, 3) { EXPECT_EQ(2, Solution().integerBreak(3)); }
18+
19+
TEST(IntegerBreak, 10) { EXPECT_EQ(36, Solution().integerBreak(10)); }

integer-break.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright (c) 2021, Christopher Friedt
3+
*
4+
* SPDX-License-Identifier: MIT
5+
*/
6+
7+
// clang-format off
8+
// name: integer-break
9+
// url: https://leetcode.com/problems/integer-break
10+
// difficulty: 2
11+
// clang-format on
12+
13+
#include <climits>
14+
#include <unordered_map>
15+
#include <vector>
16+
17+
using namespace std;
18+
19+
class Solution {
20+
public:
21+
using dp_t = unordered_map<int, int>;
22+
int integerBreak(int n) {
23+
/*
24+
Let's say we're given the number 3. How many different ways can we generate
25+
the number 3 from the sum of at least two positive integers?
26+
1 + 1 + 1, product is 1
27+
2 + 1, product is 2
28+
1 + 2, product is 2
29+
So MP(3) is 2.
30+
31+
MP(3)
32+
-1 / \ -2
33+
MP(2) MP(1)
34+
35+
We know that MP(2) is 1 and we can extrapolate that MP(1) is also 1. Then we
36+
can figure out that
37+
38+
MP(n) = max(i * MP(n - i), i * (n - i)), for i in [1, n)
39+
= 1, if n <= 2
40+
41+
It becomes evident, that for larger numbers, there is very obvious
42+
overlapping of subproblems.
43+
*/
44+
dp_t dp;
45+
dp[1] = 1;
46+
dp[2] = 1;
47+
48+
return MP(dp, n);
49+
}
50+
51+
int MP(dp_t &dp, int n) {
52+
auto it = dp.find(n);
53+
if (dp.end() != it) {
54+
return it->second;
55+
}
56+
57+
int max_product = INT_MIN;
58+
for (int i = 1; i < n; ++i) {
59+
max_product = max(max_product, i * MP(dp, n - i));
60+
max_product = max(max_product, i * (n - i));
61+
}
62+
63+
dp[n] = max_product;
64+
return max_product;
65+
}
66+
};

0 commit comments

Comments
 (0)