2

Given an array of numbers, print the number of subarrays with maximum element as x. For example :

Input :
arr = [1, 2, 3, 3, 1]
x = [3,2,1,4]

output : 11,2,2,0

Subarrays for x = 1: 
1
1

Subarrays for x = 2: 
2
1 2 

Subarrays for x = 3: 
1 2 3 
1 2 3 3 
1 2 3 3 1 
2 3 
2 3 3 
2 3 3 1 
3 
3 3 
3 3 1 
3 
3 1

There are no subarray with maximum element as 4. So for x = 4 we have to print 0.

My first attempt was to generate all subarrays and count that.The time complexity of this approach is very bad(O(n^3))

0 Answers0