1. Circular Scan for All Starting Positions (Brute Force)
Intuition
In a circular array, a subarray can start at any index i (0 <= i < n) and extend circularly for length len (1 <= len <= n). We can simulate this with two nested loops: for each start index i, we add elements at (i + j) % n and update the maximum running sum.
When to apply: Use to understand the circular wraparound geometry before applying Kadane's algorithm.
Brute Force — enumerate circular ranges
2 of 2 questions left todayEvery non-empty circular range is a candidate
Every non-empty circular range is a candidate.
public class Main { public static class Solution { public int maxSubarraySumCircular(int[] nums) { int n = nums.length; int maxSum = nums[0]; for (int i = 0; i < n; i++) { int sum = 0; for (int len = 1; len <= n; len++) { sum += nums[(i + len - 1) % n]; maxSum = Math.max(maxSum, sum); } } return maxSum; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, -2, 3, -2}; System.out.println("Max Circular Subarray Sum: " + sol.maxSubarraySumCircular(nums)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Evaluating all n start positions for up to n steps takes 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.