Kadane Algorithm for Circular Subarray Sum

🚀 Day 84 — Kadane’s Algorithm (Maximum Circular Subarray Sum) Leveling up Kadane’s pattern — today I solved the circular version of the maximum subarray problem. The twist: subarrays can wrap around the end to the beginning. 📌 Problem Solved: LeetCode 918 – Maximum Sum Circular Subarray 🧠 Key Insight – Two Cases: Case 1: The maximum subarray is non-circular (lies within the array). → Solved by standard Kadane (gmax). Case 2: The maximum subarray wraps around (takes a prefix + suffix). → Equivalent to: total sum - minimum subarray sum. Because removing the minimum contiguous segment from the middle leaves the circular max. Final answer: If all numbers are negative → gmax (since sum - gmin would be 0 or less). Else max(gmax, sum - gmin). java int min = nums[0], max = nums[0], sum = nums[0]; int gmin = nums[0], gmax = nums[0]; for (int i = 1; i < nums.length; i++) { sum += nums[i]; min = Math.min(nums[i], min + nums[i]); gmin = Math.min(gmin, min); max = Math.max(nums[i], max + nums[i]); gmax = Math.max(gmax, max); } if (gmax < 0) return gmax; return Math.max(gmax, sum - gmin); 💡 Takeaway: Kadane’s pattern is not just linear — it adapts to circular arrays by combining max subarray and min subarray with total sum. Track both extremes, and the circular case becomes elegant. No guilt about past breaks — just mastering variations, one problem at a time. #DSA #KadaneAlgorithm #CircularSubarray #LeetCode918 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic

To view or add a comment, sign in

Explore content categories