zoukankan      html  css  js  c++  java
  • 【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
    

    Constraints:

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

    解题思路:和最大的一段子数组,无外乎一下六种情况。

    1.  0;

    2. arr[i] ;

    3. sum(arr) * k ;

    4. sum(arr[i:j]) ,这种场景其实就是求最大字段和;

    5.sum(arr[i:len(arr)]) + sum(arr[0:j]) ,需要满足k>1。这种场景是第一个arr的尾部的最大值加上第二个arr头部的最大值;

    6.sum(arr[i:len(arr)]) + sum(arr[0:j]) + (k-2) * sum(arr) ,需要满足k>2。这种场景是第一个arr的尾部的最大值加上最后一个arr头部的最大值。

    代码如下:

    class Solution(object):
        def kConcatenationMaxSum(self, arr, k):
            """
            :type arr: List[int]
            :type k: int
            :rtype: int
            """
            res = 0
            left_max = []
            amount = 0
            min_sub_arr_sum = 0
            max_arr_sum = 0
            for i in arr:
                res = max(i,res)  # single item
                amount += i
                min_sub_arr_sum = min(min_sub_arr_sum, amount)
                max_arr_sum = max(max_arr_sum,amount)
                res = max(res, amount - min_sub_arr_sum)
                left_max.append(max_arr_sum)
            total_sum = amount
            res = max(res,total_sum*k) # all
            amount = 0
            max_sub_arr_sum = -float('inf')
            for i in range(len(arr) - 1, -1, -1):
                amount += arr[i]
                max_sub_arr_sum = max(max_sub_arr_sum,amount)
                res = max(res,max_sub_arr_sum + left_max[-1])
                if k > 2:
                    res = max(res,max_sub_arr_sum + left_max[-1] + (k-2)*total_sum)
            return res % (10 ** 9 + 7)
  • 相关阅读:
    UVALive 5066 Fire Drill --BFS+DP
    Codeforces 486E LIS of Sequence --树状数组求LIS
    Codeforces 460D Little Victor and Set --分类讨论+构造
    Codeforces Round #285 (Div.1 B & Div.2 D) Misha and Permutations Summation --二分+树状数组
    计算机组成原理知识总结
    HDU 5155 Harry And Magic Box --DP
    【Python数据分析】简单爬虫 爬取知乎神回复
    《查拉图斯特拉如是说》读书笔记
    POJ 3384 Feng Shui --直线切平面
    POJ 2540 Hotter Colder --半平面交
  • 原文地址:https://www.cnblogs.com/seyjs/p/11532089.html
Copyright © 2011-2022 走看看