在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer array Return the largest sum of the given array after partitioning. Example 1: Input: A = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]
Note:
给出整数数组 返回给定数组完成分隔后的最大和。 示例: 输入:A = [1,15,7,9,2,5,10], K = 3 输出:84 解释:A 变为 [15,15,15,9,10,10,10] 提示:
32ms
1 class Solution { 2 func maxSumAfterPartitioning(_ A: [Int], _ K: Int) -> Int { 3 guard A.count > 0 else { return 0 } 4 5 var dp = Array(repeating: 0, count: A.count) 6 var m = 0 7 for i in 1...A.count { 8 let j = A.count - i 9 m = max(m, A[j]) 10 if i <= K { 11 dp[j] = i * m 12 } else { 13 var result = 0 14 var localM = 0 15 for this in j..<(j + K) { 16 localM = max(localM, A[this]) 17 result = max(result, localM * (this - j + 1) + dp[this + 1]) 18 } 19 dp[j] = result 20 } 21 } 22 23 return dp[0] 24 } 25 } Runtime: 56 ms Memory Usage: 20.9 MB
1 class Solution { 2 func maxSumAfterPartitioning(_ A: [Int], _ K: Int) -> Int { 3 let n:Int = A.count 4 var dp:[Int] = [Int](repeating:0,count:n + 1) 5 for i in 1...n 6 { 7 var maxs:Int = 0 8 var j:Int = 1 9 while(j <= K && i - j >= 0) 10 { 11 maxs = max(maxs, A[i - j]) 12 dp[i] = max(dp[i], dp[i - j] + maxs * j) 13 j += 1 14 } 15 } 16 return dp[n] 17 } 18 } 64ms 1 class Solution { 2 func maxSumAfterPartitioning(_ A: [Int], _ K: Int) -> Int { 3 let N = A.count 4 var dp = [Int](repeating: 0, count: N) 5 for i in 0..<N { 6 var curMax = 0 7 for k in 1...K where i - k + 1 >= 0 { 8 curMax = max(curMax, A[i - k + 1]) 9 dp[i] = max(dp[i], (i >= k ? dp[i-k] : 0) + curMax * k) 10 } 11 } 12 return dp[N-1] 13 } 14 } 144ms 1 class Solution { 2 3 var memo = [Int: Int]() 4 func maxSumAfterPartitioning(_ A: [Int], _ K: Int) -> Int { 5 var sum_memo = [[Int]](repeating: [Int](repeating: 0, count: K), count: A.count) 6 for i in A.indices { 7 var curMax = A[i] 8 for j in 0..<K { 9 if i+j >= A.count { continue } 10 curMax = max(curMax, A[i+j]) 11 sum_memo[i][j] = curMax * (j+1) 12 } 13 } 14 return maxPartitioningSum(A, K, 0, A.count-1, sum_memo) 15 } 16 17 func maxPartitioningSum(_ A: [Int], _ K: Int, _ start: Int, _ end: Int, _ summemo: [[Int]]) -> Int { 18 if start > end { 19 return 0 20 } 21 22 if end - start < K { 23 return summemo[start][end-start] 24 } 25 var ans = 0 26 for i in start..<(start+K) { 27 let index = A.count*(i+1) + end 28 if memo[index] == nil { 29 memo[index] = maxPartitioningSum(A, K, i+1, end, summemo) 30 } 31 ans = max(ans,summemo[start][i-start] + memo[index]!) 32 } 33 return ans 34 } 35 } 152ms 1 class Solution { 2 func maxSumAfterPartitioning(_ A: [Int], _ K: Int) -> Int { 3 var dp = [Int](repeating: 0, count: A.count + 1) 4 dp[0] = 0 5 6 for i in 1...A.endIndex { 7 var m = A[i - 1] 8 for j in stride(from: i, through: max(i - K + 1, 1), by: -1) { 9 // for j in max(i-K+1, 1)...i { 10 m = max(m, A[j - 1]) 11 dp[i] = max(dp[i], (m * (i - j + 1)) + dp[j - 1]) 12 } 13 } 14 return dp.last! 15 } 16 }
|
请发表评论