Maximum subarray sum in an array created after repeated concatenation | Set | Function to find contiguous subarray with maximum sum if array is repeated K times ; Store the sum of the array arr [ ] ; Traverse the array and find sum ; Store the answer ; If K = 1 ; Apply Kadane algorithm to find sum ; Return the answer ; Stores the twice repeated array ; Traverse the range [ 0 , 2 * N ] ; Stores the maximum suffix sum ; Stores the maximum prefix sum ; Apply Kadane algorithm for 2 repetition of the array ; If the sum of the array is greater than 0 ; Return the answer ; Driver Code ; Given Input ; Function Call
def maxSubArraySumRepeated ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT curr = arr [ 0 ] NEW_LINE ans = arr [ 0 ] NEW_LINE if ( K == 1 ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT curr = max ( arr [ i ] , curr + arr [ i ] ) NEW_LINE ans = max ( ans , curr ) NEW_LINE DEDENT return ans NEW_LINE DEDENT V = [ ] NEW_LINE for i in range ( 2 * N ) : NEW_LINE INDENT V . append ( arr [ i % N ] ) NEW_LINE DEDENT maxSuf = V [ 0 ] NEW_LINE maxPref = V [ 2 * N - 1 ] NEW_LINE curr = V [ 0 ] NEW_LINE for i in range ( 1 , 2 * N , 1 ) : NEW_LINE INDENT curr += V [ i ] NEW_LINE maxPref = max ( maxPref , curr ) NEW_LINE DEDENT curr = V [ 2 * N - 1 ] NEW_LINE i = 2 * N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT curr += V [ i ] NEW_LINE maxSuf = max ( maxSuf , curr ) NEW_LINE i -= 1 NEW_LINE DEDENT curr = V [ 0 ] NEW_LINE for i in range ( 1 , 2 * N , 1 ) : NEW_LINE INDENT curr = max ( V [ i ] , curr + V [ i ] ) NEW_LINE ans = max ( ans , curr ) NEW_LINE DEDENT if ( sum > 0 ) : NEW_LINE INDENT temp = sum * ( K - 2 ) NEW_LINE ans = max ( ans , max ( temp + maxPref , temp + maxSuf ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 20 , - 30 , - 1 , 40 ] NEW_LINE N = len ( arr ) NEW_LINE K = 10 NEW_LINE print ( maxSubArraySumRepeated ( arr , N , K ) ) NEW_LINE DEDENT