Update appNew update is available. Click here to update.

Maximum subarray sum after K concatenation

Last Updated: 16 Nov, 2020
Difficulty: Moderate


Try Problem

You have been given a vector/list 'ARR' consisting of ‘N’ integers. You are also given a positive integer ‘K’.

Let’s define a vector/list 'CONCAT' of size 'N * K' formed by concatenating 'ARR' ‘K’ times. For example, if 'ARR' = [0, -1, 2] and 'K' = 3, then 'CONCAT' is given by [0, -1, 2, 0, -1, 2, 0, -1, 2].

Your task is to find the maximum possible sum of any non-empty subarray (contagious) of 'CONCAT'.

Input Format:
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.

The first line of each test case contains two single space-separated integers ‘N’ and ‘K’ representing the size of the vector/list and the given integer, respectively.

The second line of each test case contains ‘N’ single space-separated integers representing the vector elements.
Output Format :
For each test case, print an integer denoting the maximum possible subarray sum of 'CONCAT'.

Print the output of each test case in a separate line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 100
1 <= N <= 5*10^3
1 <= K <= 5*10^3    
-10^5 <= ARR[i] <= 10^5

Time Limit: 1sec

Approach 1

The main observation here is that the optimal subarray will have no prefix with negative sum. This is because we can remove the prefix with a negative sum from our optimal subarray and hence it will only increase our subarray sum/answer.


Please note, we don’t need to construct a new vector ‘CONCAT’. Since we are concatenating the given vector ‘K’ times so, ‘CONCAT[i] = ARR[i%N]’. We use this fact to solve the problem without using additional space.


The algorithm will be -

  1. We will loop from 0 to ‘N * K’ (loop variable ‘i’).
  2. We initialize ‘CUR_SUM’ (to store sum of prefix elements) to 0 and ‘MAX_SUM’ (to store maximum subarray sum) to the minimum possible value.
  3. For each iteration, we will-
    1. Add ‘ARR[i % N]’ to ‘CUR_SUM’’.
    2. Update ‘MAX_SUM’ if it’s value is less than ‘CUR_SUM’’.
    3. If ‘CUR_SUM’’ becomes negative, we will reset it to 0.
  4. Finally, we return ‘MAX_SUM’ as our answer.
Try Problem