1. Brute Force (All Subarrays with Set)
Intuition
Try every possible start tree i. For each start tree, pick fruits sequentially with tree j, adding fruit types to a set. As soon as the set contains > 2 types, break and record length j - i.
Algorithm
- Step 1: Initialize
maxFruits = 0. - Step 2: Loop i from 0 to n - 1:
- - Create set
distinct. - - Loop j from i to n - 1:
- - Add
fruits[j]todistinct. - - If
distinct.size() > 2, break. - -
maxFruits = max(maxFruits, j - i + 1). - Step 3: Return
maxFruits.
Brute Force (All Subarrays with Set) Trace
2 of 2 questions left todayPhase 1 — Window Initialization: Both left and right pointers anchor at index 0
Phase 1 — Window Initialization: Both left and right pointers anchor at index 0. Initial window length is 1 with sum/metric=2.
#include <iostream>#include <vector>#include <unordered_set>#include <algorithm> class Solution {public: int totalFruit(std::vector<int>& fruits) { int n = fruits.size(); int maxFruits = 0; for (int i = 0; i < n; i++) { std::unordered_set<int> distinct; for (int j = i; j < n; j++) { distinct.insert(fruits[j]); if (distinct.size() > 2) { break; } maxFruits = std::max(maxFruits, j - i + 1); } } return maxFruits; }}; int main() { Solution sol; std::vector<int> fruits = {1, 2, 3, 2, 2}; std::cout << "Max Fruits: " << sol.totalFruit(fruits) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (All Subarrays with Set). - Space complexity:
O(1)— Space complexity for Brute Force (All Subarrays with Set).
Why Brute Force Doesn't Scale:
For N = 100,000 trees, checking every subarray takes 1010 operations (over 10 seconds). Sliding window processes each tree at most twice (one enter, one exit), taking ~200,000 operations (< 10 ms).
For N = 100,000: Brute force takes ~10 billion operations; Sliding window completes in ~200,000 operations (~50,000x speedup).