Problem
Given an array, count the total number of strictly increasing subarrays in it.
Sample Input
[1, 2, 3, 1]
Sample Output
3
Explanation
Let’s say the endpoints of a strictly increasing subarray are
start
and
end
.
Then, the subarray
arr[start, end+1]
will be strictly increasing if the element at
end+1
is greater than the element at
end
.
The same thing goes for elements
end+1, end+2…
and so on.
C++ Programming
#include <iostream>
using namespace std;
int solve(int arr[], int n)
{
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[j - 1] >= arr[j])
{
break;
}
ans++;
}
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 3, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << solve(arr, n);
return 0;
}
Output
3
C Programming
#include <stdio.h>
int solve(int arr[], int n)
{
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[j - 1] >= arr[j])
{
break;
}
ans++;
}
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 3, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d",solve(arr, n));
return 0;
}
Output
3
Python Programming
def solve(arr): ans = 0 for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[j - 1] >= arr[j]: break ans = ans + 1 return ans arr = [1, 2, 3, 2] print(solve(arr))
Output
3
People are also reading:
- Shuffle an array according to the given order of elements
- 4–Sum Problem | Quadruplets with a given sum
- Find the smallest window in an array sorting which will make the entire array sorted
- Print all triplets that form a geometric progression
- Find the smallest subarray length whose sum of elements is >= k
- Longest Subarray with Contiguous Elements
- Find minimum sum of a subarray of size k
- Python isalpha, insumeric and isalnum(): A complete Guide
- Sort an almost sorted array where only two elements are swapped
- Reverse every consecutive m-elements of a subarray