【Leetcode 1191】 K-Concatenation Maximum Sum

本文介绍了一种解决最大子数组和问题的算法,特别是在数组重复k次后的场景中。通过分析数组的不同部分(中间、头部和尾部)来确定最大子数组的可能位置,并考虑了数组总和对结果的影响。

题目描述

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. 数组中间,多个数组拼接的结果和一个数组的结果相同。
  2. 数组头部和尾部,两个数组连起来,尾部和头部拼起来。
  3. 数组总和≥0,尾部和首部连起来,中间加上 (k-2) 个数组。

代码

class Solution {
public:
    int MOD = 1e9+7;
    
    int kConcatenationMaxSum(vector<int>& arr, int k) {
        long long res1 = maxSum(arr, 1);
        long long res2 = maxSum(arr, 2);
        
        if (k == 1) return res1;
        if (k == 2) return max(res1, res2);
        
        long long sum = accumulate(arr.begin(), arr.end(), 0LL) % MOD;
        return max(res1, max(res2, res2+(k-2)*sum)) % MOD;
    }
    
    long long maxSum(vector<int>&arr, int n) {
        long long sum = 0;
        long long ans = 0;
        while(n--) {
            for (const auto& num : arr) {
                sum = max(sum+num, 0LL) % MOD;
                ans = max(ans, sum);
            }
        }
        return ans;
    } 
};

不是很明白。。。还。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值