Minimize sum by dividing all elements of a subarray by K | Function to return the maximum subarray sum ; Function to return the minimized sum of the array elements after performing the given operation ; Find maximum subarray sum ; Find total sum of the array ; Maximum subarray sum is already negative ; Choose the subarray whose sum is maximum and divide all elements by K ; Driver code
function maxSubArraySum ( a , size ) { var max_so_far = - 1000000000 , max_ending_here = 0 ; for ( var i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } function minimizedSum ( a , n , K ) { var sum = maxSubArraySum ( a , n ) ; var totalSum = 0 ; for ( var i = 0 ; i < n ; i ++ ) totalSum += a [ i ] ; if ( sum < 0 ) return totalSum ; totalSum = totalSum - sum + sum / K ; return totalSum ; } var a = [ 1 , - 2 , 3 ] ; var n = a . length ; var K = 2 ; document . write ( minimizedSum ( a , n , K ) ) ;