1. Brute Force — Check All (Buy, Sell) Pairs
Intuition
Evaluate every possible buy day i and sell day j (where j > i), calculate profit = prices[j] - prices[i], and keep the maximum.
Algorithm
- Initialize
maxProfit = 0. - Loop
ifrom 0 to N - 2 (buy day). - Nested loop
jfrom i + 1 to N - 1 (sell day). - Calculate
profit = prices[j] - prices[i]. - Update
maxProfit = max(maxProfit, profit). - Return
maxProfit.
Approach 1: Brute Force — Check All (Buy, Sell) Pairs Trace
2 of 2 questions left todayPhase 1 — Setup: Left pointer L anchors at 0
Phase 1 — Setup: Left pointer L anchors at 0. Scanner pointer R starts traversing the array.
#include <algorithm>#include <iostream>#include <vector>using namespace std; // Brute Force: Try all buy and sell pairsint maxProfit(const vector<int>& prices) { int n = prices.size(); int maxProfitVal = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int profit = prices[j] - prices[i]; maxProfitVal = max(maxProfitVal, profit); } } return maxProfitVal;} int main() { vector<int> prices = {7, 1, 5, 3, 6, 4}; cout << "Max Profit: " << maxProfit(prices) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N²)— Nested loops inspect all N × (N - 1) / 2 pairs, leading to O(N²) quadratic time complexity. - Space complexity:
O(1)— Only scalar variables (maxProfitVal, i, j) are stored in constant memory.
Why Brute Force Doesn't Scale:
For N = 100,000 days, N² / 2 ≈ 5,000,000,000 operations (5 billion checks), exceeding the standard 1-second limit.
Key Insight: We do not need to check all historical buying days. If we sell on day i, the ONLY buying day that matters is the day with the lowest price up to day i. Maintaining a single minPrice variable reduces the complexity to a single pass.
For N = 105: Brute force takes ~5B ops (TLE). Single pass takes ~100K ops (~1ms).