[Swift]LeetCode1043. 分隔数组以得到最大和 | Partition Array for Maximum Sum
Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning.
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Example 1:
Input: A = [1,15,7,9,2,5,10], K = 3 Output: 84 Explanation: A becomes [15,15,15,9,10,10,10]
Note:
1 <= K <= A.length <= 5000 <= A[i] <= 10^6
给出整数数组 A,将该数组分隔为长度最多为 K 的几个(连续)子数组。分隔完成后,每个子数组的中的值都会变为该子数组中的最大值。
返回给定数组完成分隔后的最大和。
示例:
输入:A = [1,15,7,9,2,5,10], K = 3 输出:84 解释:A 变为 [15,15,15,9,10,10,10]
提示:
1 <= K <= A.length <= 5000 <= A[i] <= 10^6
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 }
更多精彩

