
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Subarray Product Less Than K in C++
Suppose we have given an array of positive integers nums. We have to count and print the number of (contiguous) subarrays where the product of each the elements in the subarray is less than k. So if the input is like [10,5,2,6] and k := 100, then the output will be 8. So the subarrays will be [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]]
To solve this, we will follow these steps −
- temp := 1, j := 0 and ans := 0
- for i in range 0 to size of the array
- temp := temp * nums[i]
- while temp >= k and j <= i, do
- temp := temp / nums[j]
- increase j by 1
- ans := ans + (i – j + 1)
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { lli temp = 1; int j = 0; int ans = 0; for(int i = 0; i < nums.size(); i++){ temp *= nums[i]; while(temp >= k && j <= i) { temp /= nums[j]; j++; } ans += (i - j + 1); } return ans; } }; main(){ Solution ob; vector<int> v = {10,5,2,6}; cout << (ob.numSubarrayProductLessThanK(v, 100)); }
Input
[10,5,2,6] 100
Output
8
- Related Articles
- Product of subarray just less than target in JavaScript
- Count all subsequences having product less than K in C++
- Count pairs in a sorted array whose product is less than k in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Two Sum Less Than K in Python
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Largest subarray having sum greater than k in C++
- Python – Filter Tuples Product greater than K
- Python – Elements with factors count less than K
- Count ordered pairs with product less than N in C++
- Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k in C++
- Maximum sum subarray having sum less than or equal to given sums in C++
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++
- Count of alphabets having ASCII value less than and greater than k in C++
- Maximum Product Subarray in Python

Advertisements