1. Check All Subarrays (Brute Force)
Intuition
Run two nested loops: outer loop i from 0 to n-1, and inner loop j from i to n-1. Accumulate elements in nums[i..j]. When the running sum equals k, compute length j - i + 1 and update maxLen.
When to apply: Use for small arrays to understand the problem constraints before introducing hash tables.
All Subarrays Sum (O(N^2) Time)
2 of 2 questions left todaySingle element does not equal target 3
Single element does not equal target 3.
public class Main { public static class Solution { public int maxSubArrayLen(int[] nums, int k) { int n = nums.length; int maxLen = 0; for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += nums[j]; if (sum == k) { maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, -1, 5, -2, 3}; int k = 3; System.out.println("Max Subarray Length: " + sol.maxSubArrayLen(nums, k)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Two nested loops exploring all pairs (i, j) take O(n2) operations. - Space complexity:
O(1)— Only constant extra variables are used.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.