Leetcode 1191 K-Concatenation Maximum Sum dynamic programming

Leetcode 1191 K-Concatenation Maximum Sum dynamic programming

Title Description

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

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

Problem-solving ideas

First, define a new method maxSum (k). The method of solving k == 1, and k cycle times. But time does not meet complexity requirements. The following is an optimization method.
When len (arr) == 0, 0 is returned.
When k <3, the results can be directly determined according to k.
When k <= 3, the total sum is credited arr array
when the sum <= 0, the result has maxSum (1) and maxSum (2) in both cases;
when the sum> 0, there 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)

Thanks flower sauce

Guess you like

Origin www.cnblogs.com/willwuss/p/12241983.html