Minimize sum by dividing all elements of a subarray by K | Python3 implementation of the approach ; 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
import sys NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - ( sys . maxsize - 1 ) ; NEW_LINE max_ending_here = 0 ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] ; NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here ; NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 ; NEW_LINE DEDENT DEDENT return max_so_far ; NEW_LINE DEDENT def minimizedSum ( a , n , K ) : NEW_LINE INDENT sum = maxSubArraySum ( a , n ) ; NEW_LINE totalSum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalSum += a [ i ] ; NEW_LINE DEDENT if ( sum < 0 ) : NEW_LINE INDENT return totalSum ; NEW_LINE DEDENT totalSum = totalSum - sum + sum / K ; NEW_LINE return totalSum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , - 2 , 3 ] ; NEW_LINE n = len ( a ) ; NEW_LINE K = 2 ; NEW_LINE print ( minimizedSum ( a , n , K ) ) ; NEW_LINE DEDENT