Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Count distinct elements in an array in Python
Next article icon

Count of non decreasing Arrays with ith element in range [A[i], B[i]]

Last Updated : 28 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[] both consisting of N integers, the task is to find the number of non-decreasing arrays of size N that can be formed such that each array element lies over the range [A[i], B[i]].

Examples:

Input: A[] = {1, 1}, B[] = {2, 3}
Output: 5
Explanation:
The total number of valid arrays are {1, 1}, {1, 2}, {1, 3}, {2, 2}, {2, 3}. Therefore, the count of such arrays is 5.

Input: A[] = {3, 4, 5}, B[] = {4, 5, 6}
Output: 8

 

Approach: The given problem can be solved using Dynamic Programming and Prefix Sum. Follow the steps below to solve the problem:

  • Initialize a 2D array dp[][] with values 0, where dp[i][j] denotes the total valid array till position i and with the current element as j. Initialize dp[0][0] as 1.
  • Initialize a 2D array pref[][] with values 0 to store the prefix sum of the array.
  • Iterate over the range [0, B[N - 1]] using the variable i and set the value of pref[0][i] as 1.
  • Iterate over the range [1, N] using the variable i and perform the following steps:
    • Iterate over the range [A[i - 1], B[i - 1]] using the variable j and increment the value of dp[i][j] by pref[i - 1][j] and increase the value of pref[i][j] by dp[i][j].
    • Iterate over the range [0, B[N - 1]] using the variable j and if j is greater than 0 then update the prefix sum table by incrementing the value of pref[i][j] by pref[i][j - 1].
  • Initialize the variable ans as 0 to store the resultant count of arrays formed.
  • Iterate over the range [A[N - 1], B[N - 1]] using the variable i and add the value of dp[N][i] to the variable ans.
  • After performing the above steps, print the value of ans as the answer.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to count the total number // of possible valid arrays int totalValidArrays(int a[], int b[],                      int N) {     // Make a 2D DP table     int dp[N + 1][b[N - 1] + 1];      // Make a 2D prefix sum table     int pref[N + 1][b[N - 1] + 1];      // Initialize all values to 0     memset(dp, 0, sizeof(dp)),         memset(pref, 0, sizeof(pref));      // Base Case     dp[0][0] = 1;      // Initialize the prefix values     for (int i = 0; i <= b[N - 1]; i++) {         pref[0][i] = 1;     }      // Iterate over the range and update     // the dp table accordingly     for (int i = 1; i <= N; i++) {         for (int j = a[i - 1];              j <= b[i - 1]; j++) {             dp[i][j] += pref[i - 1][j];              // Add the dp values to the             // prefix sum             pref[i][j] += dp[i][j];         }          // Update the prefix sum table         for (int j = 0; j <= b[N - 1]; j++) {             if (j > 0) {                 pref[i][j] += pref[i][j - 1];             }         }     }      // Find the result count of     // arrays formed     int ans = 0;     for (int i = a[N - 1];          i <= b[N - 1]; i++) {         ans += dp[N][i];     }      // Return the total count of arrays     return ans; }  // Driver Code int main() {     int A[] = { 1, 1 };     int B[] = { 2, 3 };     int N = sizeof(A) / sizeof(A[0]);      cout << totalValidArrays(A, B, N);      return 0; } 
Java
// Java program for the above approach public class GFG {          // Function to count the total number     // of possible valid arrays     static int totalValidArrays(int a[], int b[],                          int N)     {         // Make a 2D DP table         int dp[][] = new int[N + 1][b[N - 1] + 1];              // Make a 2D prefix sum table         int pref[][] = new int[N + 1][b[N - 1] + 1];              // Initialize all values to 0         for (int i = 0; i < N + 1; i++)              for (int j = 0; j < b[N - 1] + 1; j++)                 dp[i][j] = 0;                          for (int i = 0; i < N + 1; i++)              for (int j = 0; j < b[N - 1] + 1; j++)                 pref[i][j] = 0;                  // Base Case         dp[0][0] = 1;              // Initialize the prefix values         for (int i = 0; i <= b[N - 1]; i++) {             pref[0][i] = 1;         }              // Iterate over the range and update         // the dp table accordingly         for (int i = 1; i <= N; i++) {             for (int j = a[i - 1];                  j <= b[i - 1]; j++) {                 dp[i][j] += pref[i - 1][j];                      // Add the dp values to the                 // prefix sum                 pref[i][j] += dp[i][j];             }                  // Update the prefix sum table             for (int j = 0; j <= b[N - 1]; j++) {                 if (j > 0) {                     pref[i][j] += pref[i][j - 1];                 }             }         }              // Find the result count of         // arrays formed         int ans = 0;         for (int i = a[N - 1];              i <= b[N - 1]; i++) {             ans += dp[N][i];         }              // Return the total count of arrays         return ans;     }          // Driver Code     public static void main (String[] args)     {         int A[] = { 1, 1 };         int B[] = { 2, 3 };         int N = A.length;              System.out.println(totalValidArrays(A, B, N));     } }  // This code is contributed by AnkThon 
Python3
# python program for the above approach  # Function to count the total number # of possible valid arrays def totalValidArrays(a, b, N):      # Make a 2D DP table     dp = [[0 for _ in range(b[N - 1] + 1)] for _ in range(N + 1)]      # Make a 2D prefix sum table     pref = [[0 for _ in range(b[N - 1] + 1)] for _ in range(N + 1)]      # Base Case     dp[0][0] = 1      # Initialize the prefix values     for i in range(0, b[N - 1] + 1):         pref[0][i] = 1      # Iterate over the range and update     # the dp table accordingly     for i in range(1, N + 1):         for j in range(a[i - 1], b[i - 1] + 1):             dp[i][j] += pref[i - 1][j]              # Add the dp values to the             # prefix sum             pref[i][j] += dp[i][j]          # Update the prefix sum table         for j in range(0, b[N - 1] + 1):             if (j > 0):                 pref[i][j] += pref[i][j - 1]      # Find the result count of     # arrays formed     ans = 0     for i in range(a[N - 1], b[N - 1] + 1):         ans += dp[N][i]      # Return the total count of arrays     return ans  # Driver Code if __name__ == "__main__":      A = [1, 1]     B = [2, 3]     N = len(A)      print(totalValidArrays(A, B, N))      # This code is contributed by rakeshsahni 
C#
// C#  program for the above approach using System; class GFG  {    // Function to count the total number   // of possible valid arrays   static int totalValidArrays(int[] a, int[] b, int N)   {     // Make a 2D DP table     int[,] dp = new int[N + 1, b[N - 1] + 1];      // Make a 2D prefix sum table     int[,] pref = new int[N + 1, b[N - 1] + 1];      // Initialize all values to 0     for (int i = 0; i < N + 1; i++)        for (int j = 0; j < b[N - 1] + 1; j++)         dp[i, j] = 0;      for (int i = 0; i < N + 1; i++)        for (int j = 0; j < b[N - 1] + 1; j++)         pref[i, j] = 0;              // Base Case     dp[0, 0] = 1;      // Initialize the prefix values     for (int i = 0; i <= b[N - 1]; i++) {       pref[0, i] = 1;     }      // Iterate over the range and update     // the dp table accordingly     for (int i = 1; i <= N; i++) {       for (int j = a[i - 1];            j <= b[i - 1]; j++) {         dp[i, j] += pref[i - 1, j];          // Add the dp values to the         // prefix sum         pref[i, j] += dp[i, j];       }        // Update the prefix sum table       for (int j = 0; j <= b[N - 1]; j++) {         if (j > 0) {           pref[i, j] += pref[i, j - 1];         }       }     }      // Find the result count of     // arrays formed     int ans = 0;     for (int i = a[N - 1];          i <= b[N - 1]; i++) {       ans += dp[N, i];     }      // Return the total count of arrays     return ans;   }    // Driver Code   public static void Main ()   {        int[] A = { 1, 1 };     int[] B = { 2, 3 };     int N = A.Length;      Console.WriteLine(totalValidArrays(A, B, N));   } }  // This code is contributed by Saurabh 
JavaScript
<script>     // JavaScript program for the above approach      // Function to count the total number     // of possible valid arrays     const totalValidArrays = (a, b, N) => {         // Make a 2D DP table         let dp = new Array(N + 1).fill(0).map(() => new Array(b[N - 1] + 1).fill(0));          // Make a 2D prefix sum table         let pref = new Array(N + 1).fill(0).map(() => new Array(b[N - 1] + 1).fill(0));          // Base Case         dp[0][0] = 1;          // Initialize the prefix values         for (let i = 0; i <= b[N - 1]; i++) {             pref[0][i] = 1;         }          // Iterate over the range and update         // the dp table accordingly         for (let i = 1; i <= N; i++) {             for (let j = a[i - 1];                 j <= b[i - 1]; j++) {                 dp[i][j] += pref[i - 1][j];                  // Add the dp values to the                 // prefix sum                 pref[i][j] += dp[i][j];             }              // Update the prefix sum table             for (let j = 0; j <= b[N - 1]; j++) {                 if (j > 0) {                     pref[i][j] += pref[i][j - 1];                 }             }         }          // Find the result count of         // arrays formed         let ans = 0;         for (let i = a[N - 1];             i <= b[N - 1]; i++) {             ans += dp[N][i];         }          // Return the total count of arrays         return ans;     }      // Driver Code     let A = [1, 1];     let B = [2, 3];     let N = A.length;      document.write(totalValidArrays(A, B, N));  // This code is contributed by rakeshsahni  </script> 

Output: 
5

 

Time Complexity: O(N*M), where M is the last element of the array B[].
Auxiliary Space: O(N*M), where M is the last element of the array B[].


Next Article
Count distinct elements in an array in Python

K

kartikmodi
Improve
Article Tags :
  • Dynamic Programming
  • Mathematical
  • DSA
  • Arrays
  • array-range-queries
  • prefix-sum
  • prefix
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Mathematical
  • prefix-sum

Similar Reads

  • Count of non decreasing arrays of length N formed with values in range L to R
    Given are integers N, L and R, the task is to count the number of non decreasing arrays of length N formed with values in range [L, R] with repetition allowed.Examples: Input: N = 4, L = 4, R = 6 Output: 5 All possible arrays are {4, 4, 4, 6}, {4, 4, 5, 6}, {4, 5, 5, 6}, {4, 5, 6, 6} and {4, 6, 6, 6
    4 min read
  • Counting elements with GCD in range of A, modified to B
    Given two arrays A and B with lengths N and M respectively, the problem is to count the number of elements in array B that are equal to the greatest common divisor (gcd) of a specific range in array A, where the range is defined by two indices L and R. You are allowed to change one element in the ra
    10 min read
  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • Count of non-decreasing Arrays
    Given two arrays A[] and B[] both of size N, the task is to count the number of non-decreasing arrays C[] of size N such that for (1 ≤ i ≤ N) A[i] ≤ C[i] ≤ B[i] holds true. Array is non-decreasing if C[i] ≤ C[i + 1] holds for every i (1-based indexing) such that (1 ≤ i ≤ N - 1). Examples: Input: A[]
    15+ min read
  • Count subarrays with elements in alternate increasing-decreasing order or vice-versa
    Given an array arr[] of size N, the task is to find the count of subarrays with elements in alternate increasing-decreasing order or vice-versa. A subarray {a, b, c} will be valid if and only if either (a < b > c) or (a > b < c) is satisfied. Examples: Input: arr[] = {9, 8, 7, 6, 5}Outpu
    6 min read
  • Count of index pairs with equal elements in an array | Set 2
    Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
    8 min read
  • Minimum number of elements which are not part of Increasing or decreasing subsequence in array
    Given an array of n elements. Make strictly increasing and strictly decreasing subsequences from the array such that each array element belongs to increasing subsequence or decreasing subsequence, but not both, or can be part of none of the subsequence. Minimize the number of elements which are not
    12 min read
  • Count of subarrays for each Array element in which arr[i] is first and least
    Given an array arr[], the task is to find the count of subarrays starting from the current element that has a minimum element as the current element itself. Examples: Input: arr[] = {2, 4, 2, 1, 3} Output: {3, 1, 1, 2, 1}Explanation: For the first element we can form 3 valid subarrays with the given
    11 min read
  • Check if an array contains all elements of a given range
    An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range. Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5Output : YesInput : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6Output : NoRec
    15+ min read
  • Count of larger elements on right side of each element in an array
    Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element. Examples: Input: arr[] = {3, 7, 1, 5, 9, 2} Output: {3, 1, 3, 1, 0, 0} Explanation: For arr[0], the elements greater than it on the right are {7, 5, 9}. For arr
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences