Leetcode 1191 K-Concatenation Maximum Sum 动态规划
Posted Will
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1191 K-Concatenation Maximum Sum 动态规划相关的知识,希望对你有一定的参考价值。
Leetcode 1191 K-Concatenation Maximum Sum 动态规划
题目描述
Given an integer array arr and an integer k, modify the array by repeating it k times.
For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.
As the answer can be very large, return the answer modulo 10^9 + 7.
例子
Example 1:
Input: arr = [1,2], k = 3
Output: 9
Example 2:
Input: arr = [1,-2,1], k = 5
Output: 2
Example 3:
Input: arr = [-1,-2], k = 7
Output: 0
解题思路
首先,定义新方法maxSum(k)。根据k==1时的解题方法,循环k次即可。但不符合时间复杂度要求。以下是优化方法。
当 len(arr) == 0 时,返回0。
当 k<3 时,可根据k直接求得结果。
当 k<=3 时,记数组arr的总和为sum
当 sum <= 0 时,结果有maxSum(1)和maxSum(2)两种情况;
当 sum > 0 时, 有 maxSum(2) + (k-2)*sum.
Java代码
class Solution {
public int kConcatenationMaxSum(int[] arr, int k) {
if ( arr.length == 0 || arr == null ) return 0;
if (k < 3) return (int) (maxSum(arr, k)%(1e9+7));
long sum = 0; for(int num:arr) sum += num;
long ans = maxSum(arr, 2);
return (int) ((ans + (sum>0 ? sum:0) * (k-2))%(1e9+7));
}
private long maxSum(int[] arr, int k){
long sum=0, ans=0;
for(int i=0; i<k; i++){
for(int num : arr){
sum = Math.max(0, sum+=num);
ans = Math.max(sum, ans);
}
}
return ans;
}
}
Python代码
class Solution:
def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
def maxSum(arr, res = 0, cur = 0):
for num in arr:
res = max(0, res+num)
cur = max(cur, res)
return cur
return ( (k-2)*max(sum(arr), 0) + maxSum(arr*2) )%(10**9+7) if k>1 else maxSum(arr)%(10**9+7)
以上是关于Leetcode 1191 K-Concatenation Maximum Sum 动态规划的主要内容,如果未能解决你的问题,请参考以下文章