Count Range Sum
As a data analyst at a leading financial firm, you are tasked with identifying specific cumulative trends in stock market data. Your team is particularly interested in finding periods where the total profit or loss over a contiguous stretch of days falls within a predefined acceptable range. This analysis helps in understanding market volatility and identifying stable investment windows.
Given an integer array nums representing daily changes in stock price (where nums[i] is the change on day i), and two integers lower and upper, your task is to implement a function that returns the number of contiguous subarrays whose sum lies within the inclusive range [lower, upper].
A contiguous subarray is defined by its start and end indices i and j (inclusive, i <= j). Its sum is nums[i] + nums[i+1] + ... + nums[j].
function countRangeSum(nums: number[], lower: number, upper: number): number
nums: An array of integers representing daily changes in stock price.lower: An integer, the lower bound of the target sum range (inclusive).upper: An integer, the upper bound of the target sum range (inclusive).nums: If nums is empty, there are no subarrays, so the count should be 0.nums can contain negative, zero, or positive integers.lower > upper: If lower is strictly greater than upper, no sum can satisfy the range, so the count should be 0.number in JavaScript/TypeScript, long in Java/C++) for prefix sums to prevent overflow.Examples
Example 1
Input:
nums = [-2, 5, -1], lower = -2, upper = 2
Output:
3
Note:
The three subarrays whose sums fall in the range [-2, 2] are:
[-2] with sum -2[-1] with sum -1[-2, 5, -1] with sum 2Example 2
Input:
nums = [0], lower = 0, upper = 0
Output:
1
Note:
The subarray [0] has a sum of 0, which is within the range [0, 0].
Example 3
Input:
nums = [1, 1, 1], lower = 1, upper = 2
Output:
5
Note:
The five subarrays with sums in [1, 2] are:
[1] (index 0) sum = 1[1] (index 1) sum = 1[1] (index 2) sum = 1[1, 1] (indices 0-1) sum = 2[1, 1] (indices 1-2) sum = 2Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9-10^15 <= lower <= upper <= 10^15nums is an array of numbers, lower and upper are integers).nums).Loading editor...