#1191

K-Concatenation Maximum Sum

Medium
ArrayDynamic ProgrammingDynamic ProgrammingKadane's AlgorithmPrefix/Suffix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of creating a large array, we can leverage the properties of sub-arrays and the sum of the original array. The optimal approach uses Kadane's algorithm and considers the total sum of the array to determine the maximum sub-array sum efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Use Kadane's algorithm to find the maximum sub-array sum for k = 1.
  2. 2Step 2: Calculate the total sum of the array.
  3. 3Step 3: If k = 1, return the result from Kadane's algorithm.
  4. 4Step 4: If k > 1 and total sum > 0, consider the maximum sub-array sum from the first and last parts of the array, plus the total sum multiplied by (k-2).
  5. 5Step 5: Return the maximum value found, ensuring to take modulo 10^9 + 7.
solution.py25 lines
1def kConcatenationMaxSum(arr, k):
2    mod = 10**9 + 7
3    def kadane(arr):
4        max_sum = 0
5        current_sum = 0
6        for num in arr:
7            current_sum = max(num, current_sum + num)
8            max_sum = max(max_sum, current_sum)
9        return max_sum
10    max_k1 = kadane(arr)
11    total_sum = sum(arr)
12    if k == 1:
13        return max_k1 % mod
14    max_prefix = max_suffix = 0
15    current_sum = 0
16    for num in arr:
17        current_sum += num
18        max_suffix = max(max_suffix, current_sum)
19    current_sum = 0
20    for num in reversed(arr):
21        current_sum += num
22        max_prefix = max(max_prefix, current_sum)
23    if total_sum > 0:
24        return max(max_k1, max_prefix + max_suffix + total_sum * (k - 2)) % mod
25    return max(max_k1, max_prefix + max_suffix) % mod

Complexity note: The optimal solution runs in O(n) time because we only traverse the array a few times (for Kadane's algorithm and to calculate prefix/suffix sums).

  • 1Kadane's algorithm is essential for efficiently finding the maximum sub-array sum.
  • 2Understanding the contribution of the total sum of the array helps optimize the solution for k > 1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.