LeetCode刷题笔记 1191. K 次串联后最大子数组之和

题目描述

给你一个整数数组 arr 和一个整数 k。

首先,我们要对该数组进行修改,即把原数组 arr 重复 k 次。

举个例子,如果 arr = [1, 2] 且 k = 3,那么修改后的数组就是 [1, 2, 1, 2, 1, 2]。

然后,请你返回修改后的数组中的最大的子数组之和。

注意,子数组长度可以是 0,在这种情况下它的总和也是 0。

由于 结果可能会很大,所以需要 模(mod) 10^9 + 7 后再返回。

Sample Code

class Solution {
    public int kConcatenationMaxSum(int[] arr, int k) {
        int len = arr.length, tmp, max = 0, sum = 0, count = 2, kt = k;
        int[] dp = new int[len];
        for (int i = 0; i < len; i++)
            sum += arr[i];
        sum %= 1000000007;

        while (k > 0 && count != 0) {
            for (int i = 0; i < len; i++) {
                tmp = dp[(i - 1 + len) % len];
                dp[i] = tmp > 0 ? tmp + arr[i] : arr[i];
                max = Math.max(max, dp[i]);
            }
            k--;
            count--;
        }

        int res = max;
        for (int i = 0; i < kt - 2 && sum > 0; i++) {
            res = (res + sum) % 1000000007;
        }
        return res;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/k-concatenation-maximum-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(LeetCode笔记,#,动态规划)