FastPrepFastPrep
Problem Brief

Investable Periods 🐿️

FULLTIMEOA

A trading firm predicts the stock prices of a commodity for the next n days. A period of consecutive days is considered investable if the maximum price in the period is max_price, and the minimum price in the period is min_price. Find the number of investable periods in the next n days.

More formally, given an array price of length n, find the number of subarrays in which the maximum element is max_price and the minimum element is min_price. Note: A subarray is a sequence of consecutive elements of the array.

Function Description

Complete the function countInvestablePeriods in the editor below.

countInvestablePeriods has the following parameters:

  1. int price[n]: the predicted prices for the next n days
  2. int max_price: the maximum price of an investable period
  3. int min_price: the minimum price of an investable period

Returns

long integer: the number of investable periods

1Example 1

Input
price = [4, 5, 3, 3, 1], max_price = 5, min_price = 3
Output
4
Explanation
Here, the periods [4, 5, 3], [4, 5, 3, 3], [5, 3], and [5, 3, 3] are investable.

2Example 2

Input
price = [2, 2, 1, 5, 1], max_price = 2, min_price = 1
Output
2
Explanation
The periods [2, 2, 1] and [2, 1] are investable.

3Example 3

Input
price = [1, 2, 3, 2], max_price = 3, min_price = 2
Output
3
Explanation
Hola!! This testcase was added on the 18th of May, 2025~ You can find the source image in the problem source section below. The consecutive periods [2, 3], [2, 3, 2], and [3, 2] are investable as the min and max of these subarrays equal min_price and max_price respective. There are no otehr periods that satisfy this constraint. So, answer is 3.

Constraints

Limits and guarantees your solution can rely on.

  • 1 ≤ n ≤ 10^5
  • 1 ≤ price[i] ≤ 10^9
  • 1 ≤ min_price ≤ max_price ≤ 10^9
  • public long countInvestablePeriods(int[] price, int max_price, int min_price) {
      // write your code here
    }
    
    Input

    price

    [4, 5, 3, 3, 1]

    max_price

    5

    min_price

    3

    Output

    4

    Sign in to submit your solution.