8

Number of non-decreasing sub-arrays of length K

 3 years ago
source link: https://www.geeksforgeeks.org/number-of-non-decreasing-sub-arrays-of-length-k/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Number of non-decreasing sub-arrays of length K
  • Last Updated : 06 Nov, 2019

Given an array arr[] of length N, the task is to find the number of non-decreasing sub-arrays of length K.

Examples:

Input: arr[] = {1, 2, 3, 2, 5}, K = 2
Output: 3
{1, 2}, {2, 3} and {2, 5} are the increasing
subarrays of length 2.

Input: arr[] = {1, 2, 3, 2, 5}, K = 1
Output: 5

Naive approach Generate all the sub-arrays of length K and then check whether the sub-array satisfies the condition. Thus, the time complexity of the approach will be O(N * K).

Better approach: A better approach will be using two-pointer technique. Let’s say the current index is i.

  • Find the largest index j, such that the sub-array arr[i…j] is non-decreasing. This can be achieved by simply incrementing the value of j starting from i + 1 and checking whether arr[j] is greater than arr[j – 1].
  • Let’s say the length of the sub-array found in the previous step is L. The number of sub-arrays of length K contained in it will be max(L – K + 1, 0).
  • Now, update i = j and repeat the above steps while i is in the index range.

Below is the implementation of the above approach:

  • Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the count of
// increasing subarrays of length k
int cntSubArrays(int* arr, int n, int k)
{
// To store the final result
int res = 0;
int i = 0;
// Two pointer loop
while (i < n) {
// Initialising j
int j = i + 1;
// Looping till the subarray increases
while (j < n and arr[j] >= arr[j - 1])
j++;
// Updating the required count
res += max(j - i - k + 1, 0);
// Updating i
i = j;
}
// Returning res
return res;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 2, 5 };
int n = sizeof(arr) / sizeof(int);
int k = 2;
cout << cntSubArrays(arr, n, k);
return 0;
}
Output:
3

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK