702917. Count increasing Subarrays
Count Increasing Subarrays
Slug: count-increasing-subarrays5301
Difficulty: Easy
Id: 702917
Topic Tags: Arrays, Data Structures, sliding-window, two-pointer-algorithm
Company Tags: None
Summary
Given an array of integers, the task is to find the number of increasing subarrays in the given array. An increasing subarray is a sequence of consecutive elements that are strictly increasing.
For example, if the input array is [1, 2, 3, 4, 5], there are five increasing subarrays: [1, 2], [2, 3], [3, 4], [4, 5], and [1, 2, 3, 4, 5]. If the input array is [1, 2, 1, 3, 4, 5], there are four increasing subarrays: [1, 2], [2, 1, 3], [3, 4], and [4, 5].
Detailed Explanation
To solve this problem, we can use the sliding window approach. The idea is to maintain a counter for the number of increasing subarrays found so far.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto store the number of increasing subarrays. - Initialize two pointers,
startandend, to the beginning of the array. - Iterate through the array with the
endpointer:- For each element at index
i(represented byarr[i]), check if it is greater than the previous element (arr[i-1]). If it is, increment thecountvariable and move both pointers to the next element. - If the current element is not greater than the previous one, reset the
startpointer to the current index and continue iterating with theendpointer.
- For each element at index
- The final value of
countrepresents the number of increasing subarrays in the given array.
Time complexity: O(n), where n is the length of the input array. Space complexity: O(1), as we only use a constant amount of space to store the pointers and count variable.
Optimized Solutions
Java
public int countIncreasingSubarrays(int[] arr) {
int count = 0;
int start = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i-1]) {
count++;
start = i;
}
}
return count;
}