Sum of maximum of all subarrays by adding even frequent maximum twice | Function to calculate sum of maximum of all subarrays ; Stores the sum of maximums ; Traverse the array ; Store the frequency of the maximum element in subarray ; Finding maximum ; Increment frequency by 1 ; If new maximum is obtained ; If frequency of maximum is even , then add 2 * maxNumber . Otherwise , add maxNumber ; Print the sum obtained ; Driver Code ; Function Call
function findSum ( a ) { var ans = 0 ; for ( var low = 0 ; low < a . length ; low ++ ) { for ( var high = low ; high < a . length ; high ++ ) { var count = 0 ; var maxNumber = 0 ; for ( var i = low ; i <= high ; i ++ ) { if ( a [ i ] === maxNumber ) count ++ ; else if ( a [ i ] > maxNumber ) { maxNumber = a [ i ] ; count = 1 ; } } ans += maxNumber * ( count % 2 === 0 ? 2 : 1 ) ; } } document . write ( ans ) ; } var arr = [ 2 , 1 , 4 , 4 , 2 ] ; findSum ( arr ) ;