Count the number of strictly increasing subarrays in an array

Posted in

Count the number of strictly increasing subarrays in an array
vinaykhatri

Vinay Khatri
Last updated on February 21, 2024

    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:

    Leave a Comment on this Post

    0 Comments