Maximum Subarray Sum possible by replacing an Array element by its Square | Function to find the maximum subarray sum possible ; Stores sum without squaring ; Stores sum squaring ; Stores the maximum subarray sum ; Either extend the subarray or start a new subarray ; Either extend previous squared subarray or start a new subarray by squaring the current element ; Update maximum subarray sum ; Return answer ; Driver Code ; Function call
function getMaxSum ( a , n ) { let dp = new Array ( n ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 0 ] ; let max_sum = Math . max ( dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] ) ; for ( let i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = Math . max ( a [ i ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) ; dp [ i ] [ 1 ] = Math . max ( dp [ i - 1 ] [ 1 ] + a [ i ] , a [ i ] * a [ i ] ) ; dp [ i ] [ 1 ] = Math . max ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + a [ i ] * a [ i ] ) ; max_sum = Math . max ( max_sum , dp [ i ] [ 1 ] ) ; max_sum = Math . max ( max_sum , dp [ i ] [ 0 ] ) ; } return max_sum ; } let n = 5 ; let a = [ 1 , - 5 , 8 , 12 , - 8 ] ; document . write ( getMaxSum ( a , n ) ) ;