Sum of maximum of all subarrays by adding even frequent maximum twice | Java program for the above approach ; 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
import java . io . * ; class GFG { public static void findSum ( int a [ ] ) { int ans = 0 ; for ( int low = 0 ; low < a . length ; low ++ ) { for ( int high = low ; high < a . length ; 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 ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 4 , 4 , 2 } ; findSum ( arr ) ; } }