K-Concatenation Maximum Sum - Problem

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 109 + 7.

Input & Output

Example 1 — Basic Positive Array
$ Input: arr = [1,2], k = 3
Output: 9
💡 Note: The concatenated array is [1,2,1,2,1,2]. The maximum subarray sum is 1+2+1+2+1+2 = 9 (taking the entire array).
Example 2 — Mixed Values
$ Input: arr = [1,-2,1], k = 5
Output: 2
💡 Note: The maximum subarray sum in a single array is max(1, -2, 1, 1-2, -2+1, 1-2+1) = 1. Since total sum is 0, we don't benefit from repetitions.
Example 3 — Single Element
$ Input: arr = [-1], k = 2
Output: 0
💡 Note: All elements are negative, so the maximum subarray sum is 0 (empty subarray).

Constraints

  • 1 ≤ arr.length ≤ 105
  • 1 ≤ k ≤ 105
  • -104 ≤ arr[i] ≤ 104

Visualization

Tap to expand
K-Concatenation Maximum Sum INPUT Original Array (arr) 1 2 k = 3 Modified Array (k times) 1 2 1 2 1 2 Copy 1 Copy 2 Copy 3 Input Values arr = [1, 2] k = 3 sum(arr) = 3 ALGORITHM STEPS 1 Kadane on Single Max subarray in arr single = 3 2 Kadane on Double Max subarray in arr+arr double = 6 3 Check Array Sum If sum > 0, add (k-2)*sum 3 > 0: 6 + (3-2)*3 4 Compute Result max(single, double, extended) max(3, 6, 9) = 9 Key Formulas if k == 1: ans = single if k >= 2 and sum <= 0: ans = double else: double + (k-2)*sum FINAL RESULT Maximum Subarray (entire array) 1 2 1 2 1 2 1 + 2 + 1 + 2 + 1 + 2 = 9 Output 9 Calculation Breakdown Single array max: 3 Double array max: 6 Sum is positive (3 > 0) Extended: 6 + (3-2)*3 = 9 OK Key Insight: For k >= 2: If array sum is positive, max subarray can span multiple copies. Use Kadane's algorithm on two concatenated arrays to find prefix/suffix sums, then add (k-2) * sum for middle copies. Time: O(n), Space: O(1). Handle negative sums by taking max(0, result) and apply modulo 10^9 + 7. TutorialsPoint - K-Concatenation Maximum Sum | Optimal Solution
Asked in
Facebook 15 Google 12
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen