Sum of maximum of all subarrays by adding even frequent maximum twice | C ++ program for the above approach ; Function to calculate sum of maximum of all subarrays ; Storeas 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( vector < int > a ) { int ans = 0 ; for ( int low = 0 ; low < a . size ( ) ; low ++ ) { for ( int high = low ; high < a . size ( ) ; high ++ ) { int count = 0 ; int maxNumber = 0 ; for ( int 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 ) ; } } cout << ( ans ) ; } int main ( ) { vector < int > arr = { 2 , 1 , 4 , 4 , 2 } ; findSum ( arr ) ; }