1. Nested Loops
Intuition
Use two nested loops to check all pairs (i, j) with 0 <= i < j < n. For each pair, check if (long long)nums[i] > 2LL \cdot nums[j]. Because there are \frac{n(n - 1)}{2} pairs, this runs in O(n2) time, which times out for n = 50,000.
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: Loop j from i + 1 to n - 1.
- Step 4: If (long)nums[i] > 2L * nums[j], increment count.
- Step 5: Return count.
#include <iostream>#include <vector> int reversePairsBrute(const std::vector<int>& nums) { int n = nums.size(); int count = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if ((long long)nums[i] > 2LL * nums[j]) { count++; } } } return count;} int main() { std::vector<int> nums = {1, 3, 2, 3, 1}; std::cout << reversePairsBrute(nums) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^2) where n is nums length - Space complexity:
O(1) auxiliary space