
Problem
Solution
Submissions
Range Sum
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to count the number of range sums that lie in a given range [lower, upper] inclusive. Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums from indices i to j inclusive, where i <= j.
Example 1
- Input: nums = [-2,5,-1], lower = -2, upper = 2
- Output: 3
- Explanation:
Step 1: Calculate all possible range sums
Step 2: S(0,0) = -2, S(0,1) = 3, S(0,2) = 2, S(1,1) = 5, S(1,2) = 4, S(2,2) = -1
Step 3: Range sums in [-2, 2]: S(0,0) = -2, S(0,2) = 2, S(2,2) = -1
Step 4: Therefore, count = 3
Example 2
- Input: nums = [0], lower = 0, upper = 0
- Output: 1
- Explanation:
Step 1: Only one element in array
Step 2: S(0,0) = 0
Step 3: 0 lies within range [0, 0]
Step 4: Therefore, count = 1
Constraints
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- -10^5 <= lower <= upper <= 10^5
- Time Complexity: O(n^2) for brute force approach
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use nested loops to generate all possible range sums
- For each starting index i, calculate cumulative sum to all ending indices j >= i
- Check if each range sum falls within [lower, upper]
- Keep a counter for valid range sums
- Use long long to avoid integer overflow during sum calculations