Open In App
Related Articles

Number of non-decreasing sub-arrays of length less than or equal to K

Improve Article
Improve
Save Article
Save
Like Article
Like

Given an array arr[] of N elements and an integer K, the task is to find the number of non-decreasing sub-arrays of length less than or equal to K.
Examples: 

Input: arr[] = {1, 2, 3}, K = 2 
Output:
{1}, {2}, {3}, {1, 2} and {2, 3} are the valid subarrays.
Input: arr[] = {3, 2, 1}, K = 1 
Output:

Naive approach: A simple approach is to generate all the sub-arrays of length less than or equal to K and then check whether the sub-array satisfies the condition. Thus, the time complexity of the approach will be O(N3).
Efficient approach: A better approach will be using the two-pointer technique
 

  • For any index i, find the largest index j such that the sub-array arr[i…j] is non-decreasing. This can be achieved by simply increasing the value of j, starting from i + 1 and checking whether arr[j] is greater than arr[j – 1].
  • Lets say that the length of the sub-array found in the previous step is L. Calculate X = max(0, L – K) and (L * (L + 1)) / 2 – (X * (X + 1)) / 2 will be added to the final answer. This is because for an array of length L, the number of sub-arrays with length ? K
    • Number of such sub-arrays starting from the first element = L – K = X.
    • Number of such sub-arrays starting from the second element = L – K – 1 = X – 1.
    • Number of such sub-arrays starting from the third element = L – K – 2 = X – 2.
    • And so on until 0 i.e. 1 + 2 + 3 + .. + X = (X * (X + 1)) / 2. If this value is subtracted from the total increasing subarrays then the result will be the count of increasing subarrays of length less than or equal to K

Below is the implementation of the above approach: 
 

C++




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


Java




// Java implementation of the approach
class GFG
{
 
// Function to return the required count
static int findCnt(int[] arr, int n, int k)
{
    // To store the final result
    int ret = 0;
 
    // Two pointer loop
    int i = 0;
    while (i < n)
    {
 
        // Initialising j
        int j = i + 1;
 
        // Looping till the subarray increases
        while (j < n && arr[j] >= arr[j - 1])
            j++;
        int x = Math.max(0, j - i - k);
 
        // Update ret
        ret += ((j - i) * (j - i + 1)) / 2 -
                          (x * (x + 1)) / 2;
 
        // Update i
        i = j;
    }
 
    // Return ret
    return ret;
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = { 1, 2, 3 };
    int n = arr.length;
    int k = 2;
 
    System.out.println(findCnt(arr, n, k));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
 
# Function to return the required count
def findCnt(arr, n, k) :
 
    # To store the final result
    ret = 0;
 
    # Two pointer loop
    i = 0;
    while (i < n) :
 
        # Initialising j
        j = i + 1;
 
        # Looping till the subarray increases
        while (j < n and arr[j] >= arr[j - 1]) :
            j += 1;
             
        x = max(0, j - i - k);
 
        # Update ret
        ret += ((j - i) * (j - i + 1)) // 2 - \
                          (x * (x + 1)) / 2;
 
        # Update i
        i = j;
 
    # Return ret
    return ret;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3 ];
    n = len(arr);
    k = 2;
 
    print(findCnt(arr, n, k));
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
                     
class GFG
{
 
// Function to return the required count
static int findCnt(int[] arr, int n, int k)
{
    // To store the final result
    int ret = 0;
 
    // Two pointer loop
    int i = 0;
    while (i < n)
    {
 
        // Initialising j
        int j = i + 1;
 
        // Looping till the subarray increases
        while (j < n && arr[j] >= arr[j - 1])
            j++;
        int x = Math.Max(0, j - i - k);
 
        // Update ret
        ret += ((j - i) * (j - i + 1)) / 2 -
                        (x * (x + 1)) / 2;
 
        // Update i
        i = j;
    }
 
    // Return ret
    return ret;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 1, 2, 3 };
    int n = arr.Length;
    int k = 2;
 
    Console.WriteLine(findCnt(arr, n, k));
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the required count
function findCnt(arr, n, k)
{
    // To store the final result
    var ret = 0;
 
    // Two pointer loop
    var i = 0;
    while (i < n) {
 
        // Initialising j
        var j = i + 1;
 
        // Looping till the subarray increases
        while (j < n && arr[j] >= arr[j - 1])
            j++;
        var x = Math.max(0, j - i - k);
 
        // Update ret
        ret += ((j - i) * (j - i + 1)) / 2 - (x * (x + 1)) / 2;
 
        // Update i
        i = j;
    }
 
    // Return ret
    return ret;
}
 
// Driver code
var arr = [1, 2, 3 ];
var n = arr.length;
var k = 2;
document.write( findCnt(arr, n, k));
 
</script>


Output: 

5

 

Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 22 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials