BackmediumArrays Razorpay

Consecutive Subarray Product Solution

Problem Statement

Given an array of integers and a number k, find the length of the longest subarray where the product of all elements is less than or equal to k.

Example 1
Input
[1, 2, 3, 4, 5, 100]
Output
3

Explanation: Step-by-step: We start with the subarray [1, 2, 3, 4, 5]. The product of this subarray is 120 which is greater than k=100. We move the left pointer to the right until the product of the subarray is less than or equal to k. The longest subarray with product <= k is [1, 2, 3] with product 6 which is <= k.

Example 2
Input
[5, 5, 5, 5, 5, 25]
Output
1

Explanation: Step-by-step: We start with the subarray [5, 5, 5, 5, 5, 25]. The product of this subarray is 3125 which is greater than k=25. We move the left pointer to the right until the product of the subarray is less than or equal to k. The longest subarray with product <= k is [5] with product 5 which is <= k.

Constraints

  • 1 ≤ array size ≤ 10^5
  • 1 ≤ array elements ≤ 10^3
  • 1 ≤ k ≤ 10^6
  • Array may contain duplicate elements
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free