Problem Description
Given an integer array arr and an integer k, repeat the array k times to form a new array and return the maximum sub-array sum of this concatenated array. Note that the sub-array may be empty (with sum 0), and since the answer can be very large, return the result modulo 10^9+7.
Key Insights
- Use Kadane's algorithm to determine the maximum subarray sum for one copy of the array.
- Calculate the total sum of the original array.
- For k >= 2, compute the maximum prefix sum (maximum sum starting at index 0) and the maximum suffix sum (maximum sum ending at the last index).
- If the total sum of the array is positive, then adding (k-2) full copies (i.e. total sum multiplied by k-2) between the suffix and prefix can boost the maximum sum.
- Always consider the possibility of an empty subarray (0) if all numbers are negative.
Space and Time Complexity
Time Complexity: O(n), where n is the length of arr (iterating a few times over arr). Space Complexity: O(1), using only a few extra variables.
Solution
The solution uses Kadane's algorithm to find the maximum subarray sum in one copy of the array. For k > 1, the idea is to connect the end of one copy with the beginning of the next copy by computing the maximum prefix sum and maximum suffix sum. If the total sum of arr is positive, then the optimal result might span across multiple copies: suffix from the first copy + (k-2 copies worth of total sum) + prefix from the last copy. The final answer is the maximum of this combined sum and the maximum subarray sum within one or two concatenated copies. Finally, return the result modulo 10^9+7.