![]() |
VOOZH | about |
Given an array arr[], Find the number of subarrays whose first element is not greater than other elements of the subarray.
Examples:
Input: arr[] = [1, 2, 1]
Output: 5
Explanation: All subarray are: {1}, {1, 2}, {1, 2, 1}, {2}, {2, 1}, {1}
From above subarray the following meets the condition: {1}, {1, 2}, {1, 2, 1}, {2}, {1}Input: arr[] = [1, 3, 5, 2]
Output: 8
Explanation: We have the following subarrays which meet the condition:
{1}, {1, 3}, {1, 3, 5}, {1, 3, 5, 2}, {3}, {3, 5}, {5}, {2}
Table of Content
The naive approach is to run a nested loop and find all the subarrays with first element not bigger than the other elements in the subarray.
8
We donβt need to find the minimum separately after two loops. While expanding the subarray, we can directly maintain the running minimum and check if it stays β₯ the first element.
8
The efficient approach is based on the concept of finding the next smaller element on the right of an element.
Working:
8