1. Nested Loops on Subarrays
Intuition
For every starting index i from 0 to n - 1, maintain a running sum as j goes from i to n - 1.
Check if lower <= currentSum <= upper.
Because there are O(n2) subarrays, this approach runs in O(n2) time and O(1) space, resulting in Time Limit Exceeded for n = 105.
When to apply: Feasible only when n <= 2000.
Algorithm
- Step 1: Initialize count = 0.
- Step 2: Loop i from 0 to n - 1.
- Step 3: Maintain running sum starting at 0, loop j from i to n - 1 adding nums[j].
- Step 4: If running sum >= lower and running sum <= upper, increment count.
- Step 5: Return count.
#include <iostream>#include <vector> int countRangeSumBrute(const std::vector<int>& nums, int lower, int upper) { int n = nums.size(); int count = 0; for (int i = 0; i < n; ++i) { long long sum = 0; for (int j = i; j < n; ++j) { sum += nums[j]; if (sum >= lower && sum <= upper) { count++; } } } return count;} int main() { std::vector<int> nums = {-2, 5, -1}; std::cout << countRangeSumBrute(nums, -2, 2) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^2) where n is the number of elements - Space complexity:
O(1) auxiliary space