Compute maximum of the function efficiently over all sub | JavaScript 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
const MAX = 100005 ; function kadaneAlgorithm ( ar , n ) { let sum = 0 , maxSum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum += ar [ i ] ; if ( sum < 0 ) sum = 0 ; maxSum = Math . max ( maxSum , sum ) ; } return maxSum ; } function maxFunction ( arr , n ) { let b = new Array ( MAX ) , c = new Array ( MAX ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( i & 1 ) { b [ i ] = Math . abs ( arr [ i + 1 ] - arr [ i ] ) ; c [ i ] = - b [ i ] ; } else { c [ i ] = Math . abs ( arr [ i + 1 ] - arr [ i ] ) ; b [ i ] = - c [ i ] ; } } let ans = kadaneAlgorithm ( b , n - 1 ) ; ans = Math . max ( ans , kadaneAlgorithm ( c , n - 1 ) ) ; return ans ; } let arr = [ 1 , 5 , 4 , 7 ] ; let n = arr . length ; document . write ( maxFunction ( arr , n ) ) ;