text: Maximum subarray sum in an array created after repeated concatenation | Set | C # program for the above approach ; 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
code: using System ; using System . Collections . Generic ; class GFG { static int maxSubArraySumRepeated ( int [ ] arr , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; int curr = arr [ 0 ] ; int ans = arr [ 0 ] ; if ( K == 1 ) { for ( int i = 1 ; i < N ; i ++ ) { curr = Math . Max ( arr [ i ] , curr + arr [ i ] ) ; ans = Math . Max ( ans , curr ) ; } return ans ; } List < int > V = new List < int > ( ) ; for ( int i = 0 ; i < 2 * N ; i ++ ) { V . Add ( arr [ i % N ] ) ; } int maxSuf = V [ 0 ] ; int maxPref = V [ 2 * N - 1 ] ; curr = V [ 0 ] ; for ( int i = 1 ; i < 2 * N ; i ++ ) { curr += V [ i ] ; maxPref = Math . Max ( maxPref , curr ) ; } curr = V [ 2 * N - 1 ] ; for ( int i = 2 * N - 2 ; i >= 0 ; i -- ) { curr += V [ i ] ; maxSuf = Math . Max ( maxSuf , curr ) ; } curr = V [ 0 ] ; for ( int i = 1 ; i < 2 * N ; i ++ ) { curr = Math . Max ( V [ i ] , curr + V [ i ] ) ; ans = Math . Max ( ans , curr ) ; } if ( sum > 0 ) { int temp = sum * ( K - 2 ) ; ans = Math . Max ( ans , Math . Max ( temp + maxPref , temp + maxSuf ) ) ; } return ans ; } public static void Main ( ) { int [ ] arr = { 10 , 20 , - 30 , - 1 , 40 } ; int N = arr . Length ; int K = 10 ; Console . WriteLine ( maxSubArraySumRepeated ( arr , N , K ) ) ; } }