![]() |
VOOZH | about |
Given an integer array arr[], count the number of subarrays in arr[] that are strictly increasing and have a size of at least 2. A subarray is a contiguous sequence of elements from arr[]. A subarray is strictly increasing if each element is greater than its previous element.
Examples:
Input: arr[] = [1, 4, 5, 3, 7, 9]
Output: 6
Explanation: The strictly increasing subarrays are: [1, 4], [1, 4, 5], [4, 5], [3, 7], [3, 7, 9], [7, 9]Input: arr[] = [1, 3, 3, 2, 3, 5]
Output: 4
Explanation: The strictly increasing subarrays are: [1, 3], [2, 3], [2, 3, 5], [3, 5]Input: arr[] = [2, 2, 2, 2]
Output: 0
Explanation: No strictly increasing subarray exists.
Table of Content
Count all strictly increasing subarrays by starting from each index i and expanding forward. For every starting point, we use another pointer j to extend the subarray as long as the elements keep increasing. As soon as the increasing order breaks, we stop extending from that starting point and move to the next index.
6
We can do only with a single pass. Instead of checking every subarray explicitly, we track the length of increasing segments using len. When a decreasing element is encountered, we use the formula (len * (len - 1)) / 2 to count subarrays formed by the segment and then reset len. Finally, we add the remaining subarrays after the loop ends.
Steps to implement the above idea:
6