1. Brute Force (Recursive Branching)
Intuition
Recursively explore picking the left element nums[left] or right element nums[right]. Return the minimum steps among valid branches.
Algorithm
- Step 1: In helper
dfs(left, right, remX, steps): - - If
remX == 0, returnsteps. - - If
remX < 0orleft > right, returnINF. - - Recurse left:
dfs(left + 1, right, remX - nums[left], steps + 1). - - Recurse right:
dfs(left, right - 1, remX - nums[right], steps + 1). - - Return
min(pickLeft, pickRight). - Step 2: Return result or -1 if INF.
Prefix/Suffix Combinations (O(N^2) Time)
2 of 2 questions left todayPrefix [1, 1, 4] alone has sum 6, which overshoots x
Prefix [1, 1, 4] alone has sum 6, which overshoots x.
#include <iostream>#include <vector>#include <algorithm> class Solution {private: const int INF = 1e9; int dfs(const std::vector<int>& nums, int left, int right, int x, int steps) { if (x == 0) return steps; if (x < 0 || left > right) return INF; int pickLeft = dfs(nums, left + 1, right, x - nums[left], steps + 1); int pickRight = dfs(nums, left, right - 1, x - nums[right], steps + 1); return std::min(pickLeft, pickRight); } public: int minOperations(std::vector<int>& nums, int x) { int res = dfs(nums, 0, (int)nums.size() - 1, x, 0); return res >= INF ? -1 : res; }}; int main() { Solution sol; std::vector<int> nums = {1, 1, 4, 2, 3}; std::cout << "Min Operations: " << sol.minOperations(nums, 5) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Recursive Branching). - Space complexity:
O(1)— Space complexity for Brute Force (Recursive Branching).
Why Brute Force Doesn't Scale:
DFS takes O(2N) steps, which for N = 100,000 exceeds 2100000. Inverting to middle subarray sliding window reduces the entire problem to a single linear pass of 200,000 pointer operations.
For N = 100,000: DFS hangs indefinitely; Two-pointer sliding window completes in ~3 milliseconds.