Find the index in a circular array from which prefix sum is always non | Function to find the starting index of the given circular array s . t . prefix sum array is non negative ; Stores the sum of the array ; Stores the starting index ; Stores the minimum prefix sum of A [ 0. . i ] ; Traverse the array arr ; Update the value of sum ; If sum is less than min ; Update the min as the value of prefix sum ; Update in ; Otherwise , no such index is possible ; Driver Code
function startingPoint ( A , N ) { var sum = 0 ; var it = 0 ; var min = Number . MAX_VALUE ; for ( i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( sum < min ) { min = sum ; it = i + 1 ; } } if ( sum < 0 ) { return - 1 ; } return it % N ; } var arr = [ 3 , - 6 , 7 , - 4 , - 4 , 6 , - 1 ] ; var N = arr . length ; document . write ( startingPoint ( arr , N ) ) ;