40
40
41
41
** 方法一:动态规划**
42
42
43
- 设 dp[ i] 表示正整数 n 能获得的最大乘积,初始化 ` dp[1] = 1 ` 。
43
+ 我们定义 $ dp[ i] $ 表示正整数 $n$ 能获得的最大乘积,初始化 $ dp[ 1] = 1$。答案即为 $dp [ n ] $ 。
44
44
45
- ` i >= 2 ` 时,` dp[i] = max(dp[i], dp[i - j] * j, (i - j) * j) ` (` j∈[0, i) ` )。
45
+ 状态转移方程为:
46
+
47
+ $$
48
+ dp[i] = max(dp[i], dp[i - j] * j, (i - j) * j) \quad (j \in [0, i))
49
+ $$
50
+
51
+ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为正整数 $n$。
52
+
53
+ ** 方法二:数学**
54
+
55
+ 当 $n \lt 4$ 时,$n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。
56
+
57
+ 时间复杂度 $O(1)$,空间复杂度 $O(1)$。
46
58
47
59
<!-- tabs:start -->
48
60
@@ -60,6 +72,18 @@ class Solution:
60
72
return dp[n]
61
73
```
62
74
75
+ ``` python
76
+ class Solution :
77
+ def integerBreak (self , n : int ) -> int :
78
+ if n < 4 :
79
+ return n - 1
80
+ if n % 3 == 0 :
81
+ return pow (3 , n // 3 )
82
+ if n % 3 == 1 :
83
+ return pow (3 , n // 3 - 1 ) * 4
84
+ return pow (3 , n // 3 ) * 2
85
+ ```
86
+
63
87
### ** Java**
64
88
65
89
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -79,6 +103,23 @@ class Solution {
79
103
}
80
104
```
81
105
106
+ ``` java
107
+ class Solution {
108
+ public int integerBreak (int n ) {
109
+ if (n < 4 ) {
110
+ return n - 1 ;
111
+ }
112
+ if (n % 3 == 0 ) {
113
+ return (int ) Math . pow(3 , n / 3 );
114
+ }
115
+ if (n % 3 == 1 ) {
116
+ return (int ) Math . pow(3 , n / 3 - 1 ) * 4 ;
117
+ }
118
+ return (int ) Math . pow(3 , n / 3 ) * 2 ;
119
+ }
120
+ }
121
+ ```
122
+
82
123
### ** C++**
83
124
84
125
``` cpp
@@ -97,6 +138,24 @@ public:
97
138
};
98
139
```
99
140
141
+ ```cpp
142
+ class Solution {
143
+ public:
144
+ int integerBreak(int n) {
145
+ if (n < 4) {
146
+ return n - 1;
147
+ }
148
+ if (n % 3 == 0) {
149
+ return pow(3, n / 3);
150
+ }
151
+ if (n % 3 == 1) {
152
+ return pow(3, n / 3 - 1) * 4;
153
+ }
154
+ return pow(3, n / 3) * 2;
155
+ }
156
+ };
157
+ ```
158
+
100
159
### ** Go**
101
160
102
161
``` go
@@ -119,6 +178,21 @@ func max(a, b int) int {
119
178
}
120
179
```
121
180
181
+ ``` go
182
+ func integerBreak (n int ) int {
183
+ if n < 4 {
184
+ return n - 1
185
+ }
186
+ if n%3 == 0 {
187
+ return int (math.Pow (3 , float64 (n/3 )))
188
+ }
189
+ if n%3 == 1 {
190
+ return int (math.Pow (3 , float64 (n/3 -1 ))) * 4
191
+ }
192
+ return int (math.Pow (3 , float64 (n/3 ))) * 2
193
+ }
194
+ ```
195
+
122
196
### ** C**
123
197
124
198
``` c
@@ -159,6 +233,22 @@ function integerBreak(n: number): number {
159
233
}
160
234
```
161
235
236
+ ``` ts
237
+ function integerBreak(n : number ): number {
238
+ if (n < 4 ) {
239
+ return n - 1 ;
240
+ }
241
+ const m = Math .floor (n / 3 );
242
+ if (n % 3 == 0 ) {
243
+ return 3 ** m ;
244
+ }
245
+ if (n % 3 == 1 ) {
246
+ return 3 ** (m - 1 ) * 4 ;
247
+ }
248
+ return 3 ** m * 2 ;
249
+ }
250
+ ```
251
+
162
252
### ** ...**
163
253
164
254
```
0 commit comments