Compute maximum of the function efficiently over all sub | Python3 implementation of the above approach ; Function to return maximum sum of a sub - array ; Function to return maximum value of function F ; Compute arrays B [ ] and C [ ] ; Find maximum sum sub - array of both of the arrays and take maximum among them ; Driver code
MAX = 100005 ; NEW_LINE def kadaneAlgorithm ( ar , n ) : NEW_LINE INDENT sum = 0 ; maxSum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ar [ i ] ; NEW_LINE if ( sum < 0 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE DEDENT maxSum = max ( maxSum , sum ) ; NEW_LINE DEDENT return maxSum ; NEW_LINE DEDENT def maxFunction ( arr , n ) : NEW_LINE INDENT b = [ 0 ] * MAX ; NEW_LINE c = [ 0 ] * MAX ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT b [ i ] = abs ( arr [ i + 1 ] - arr [ i ] ) ; NEW_LINE c [ i ] = - b [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT c [ i ] = abs ( arr [ i + 1 ] - arr [ i ] ) ; NEW_LINE b [ i ] = - c [ i ] ; NEW_LINE DEDENT DEDENT ans = kadaneAlgorithm ( b , n - 1 ) ; NEW_LINE ans = max ( ans , kadaneAlgorithm ( c , n - 1 ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 4 , 7 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( maxFunction ( arr , n ) ) ; NEW_LINE DEDENT