Leetcode 1191. K-Concatenation Maximum Sum

Posted zhaoyinghe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1191. K-Concatenation Maximum Sum相关的知识,希望对你有一定的参考价值。

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 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

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4

参考Maximum Sum Circular Subarray,可分为以下三种情况:

  1. 最大子数组和在输入数组的中间;
  2. 最大子数组和由输入数组的头尾部分组成;
  3. 最大子数组和跨越中间跨越多个输入数组。
    技术图片

其中,第三种情况可以看作是第二种情况的结果假设(k-2)*sum(arr),即子数组和大于0时,第三种情况时肯定大于第二种情况的。最终结果取上面三种情况种的最大值即可。

class Solution:
    def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
        mod = pow(10, 9)+7
        # 计算最大子数组和以及数组和
        cur_max, total, max_sum = 0, 0, 0
        for num in arr:
            cur_max = max(cur_max+num, num)
            max_sum = max(max_sum, cur_max)   
            total += num
        
        if k == 1:
            return max_sum%mod
        
        # 计算最大前缀和
        prefix_sum = 0
        cur_sum = 0
        for i in range(len(arr)):
            cur_sum += arr[i]
            prefix_sum = max(cur_sum, prefix_sum)
        
        #计算最大后缀和
        suffix_sum = 0
        cur_sum = 0
        for i in range(len(arr))[::-1]:
            cur_sum += arr[i]
            suffix_sum = max(cur_sum, suffix_sum)
        
        if total > 0:
            print(prefix_sum, suffix_sum, total)
            return max(((k-2)*total+prefix_sum+suffix_sum)%mod, max_sum%mod)
        else:
            print(prefix_sum, suffix_sum, total)
            return max((prefix_sum+suffix_sum)%mod, max_sum%mod)

参考资料

  1. https://leetcode.com/problems/k-concatenation-maximum-sum/
  2. https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/382350/Java-Solution(Kadens-Algo)-with-Explanation
  3. https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/382429/C%2B%2B-O(N)-time-O(1)-space-with-ExplanationPicture

类似题目:

  1. Maximum Sum Circular Subarray

以上是关于Leetcode 1191. K-Concatenation Maximum Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode.1191 K 次串联后最大子数组之和

1191:流感传染

1191 数轴染色

POJ 1191 棋盘分割(DP)

codevs 1191 数轴染色

bzoj 1191 超级英雄Hero