leetcode 343. 整数拆分

题解

动态规划,dp数组保存最大乘积

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func integerBreak(n int) int {
dp := make([]int, n+1)
dp[1], dp[2] = 1, 1
for i := 3; i <= n; i++ {
for j := 1; j <= i/2; j++ {
tmp := max(dp[j], j) * max(dp[i-j], i-j)
dp[i] = max(dp[i], tmp)
}
}
return dp[n]
}

func max(a, b int) int {
if a > b {
return a
}
return b
}