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
def findSum ( a ) : NEW_LINE INDENT ans = 0 NEW_LINE for low in range ( 0 , len ( a ) ) : NEW_LINE INDENT for high in range ( low , len ( a ) ) : NEW_LINE count = 0 NEW_LINE maxNumber = 0 NEW_LINE for i in range ( low , high + 1 ) : NEW_LINE INDENT if ( a [ i ] == maxNumber ) : NEW_LINE count += 1 NEW_LINE elif ( a [ i ] > maxNumber ) : NEW_LINE maxNumber = a [ i ] NEW_LINE count = 1 NEW_LINE DEDENT if count % 2 : NEW_LINE INDENT ans += maxNumber NEW_LINE DEDENT else : NEW_LINE INDENT ans += maxNumber * 2 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 4 , 2 ] NEW_LINE findSum ( arr ) NEW_LINE