🚀 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
Kadane Algorithm for Circular Subarray Sum
More Relevant Posts
-
🚀 Day 80 — Kadane’s Algorithm (Maximum Subarray) Continuing the Kadane pattern — today I implemented the classic Maximum Subarray Sum problem. This is where the “ending at index i” logic truly shines. 📌 Problem Solved: LeetCode 53 – Maximum Subarray 🧠 Kadane’s in Action: java int max = nums[0], gmax = nums[0]; for (int i = 1; i < nums.length; i++) { max = Math.max(nums[i], max + nums[i]); gmax = Math.max(gmax, max); } return gmax; Step‑by‑step logic: max = best sum of subarray ending at current index. At each i, we choose: extend previous subarray (max + nums[i]) or start fresh (nums[i]). gmax tracks the global maximum across all endings. Why this works even with negatives: Because we always have the option to discard the past and start fresh, Kadane’s never gets stuck with a losing streak. 💡 Takeaway: Three lines of code, but behind them lies a powerful pattern. Understanding the why (the decision at each index) makes it easy to adapt to variations like minimum subarray or maximum product. No guilt about past breaks — just building pattern recognition one day at a time. #DSA #KadaneAlgorithm #MaximumSubarray #LeetCode53 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 83 — Kadane’s Algorithm (Maximum Absolute Subarray Sum) Taking Kadane’s pattern one step further — today I solved a problem that asks for the maximum absolute sum of any subarray. The absolute value adds a twist: the largest magnitude could come from a very positive sum or a very negative sum. 📌 Problem Solved: LeetCode 1749 – Maximum Absolute Sum of Any Subarray 🧠 The Approach – Track Both Extremes: java int max = nums[0], min = nums[0], ans = nums[0]; for (int i = 1; i < nums.length; i++) { max = Math.max(nums[i], max + nums[i]); min = Math.min(nums[i], min + nums[i]); ans = Math.max(ans, Math.max(Math.abs(max), Math.abs(min))); } return Math.abs(ans); Why this works: max tracks the maximum subarray sum ending at i (standard Kadane). min tracks the minimum subarray sum ending at i (Kadane for minimum). The absolute sum could be either |max| or |min| (since a large negative sum has a large absolute value). ans keeps the largest of these absolute values across all endings. 💡 Key Insight: When the problem asks for “maximum absolute” or “closest to zero” etc., often you need to track both the maximum and minimum subarray sums simultaneously. Kadane’s pattern is flexible enough to handle this with just two variables. No guilt about past breaks — just adding another tool to the Kadane toolbox. #DSA #KadaneAlgorithm #MaximumAbsoluteSum #LeetCode1749 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 81 — Kadane’s Algorithm (Minimum Subarray Sum) Extending the Kadane pattern — today I solved the minimum sum version of the contiguous subarray problem. The logic is identical to maximum subarray, just flipping max to min. 📌 Problem Solved: GeeksforGeeks – Smallest Sum Contiguous Subarray 🧠 Kadane’s for Minimum Sum: java int min = a[0], ans = a[0]; for (int i = 1; i < a.length; i++) { min = Math.min(a[i], a[i] + min); ans = Math.min(ans, min); } return ans; Step‑by‑step logic: min = best sum of subarray ending at current index (minimum possible). At each i, choose: extend previous subarray (min + a[i]) or start fresh (a[i]). ans tracks the global minimum across all endings. Why this works: Same as maximum subarray, but we always pick the smaller option. Negatives become desirable here, and positives may cause us to start fresh. 💡 Takeaway: Kadane’s is a template — Math.max for maximum sum, Math.min for minimum sum. Understand the decision at each index, and you can solve both variations effortlessly. No guilt about past breaks — just mastering patterns one variation at a time. #DSA #KadaneAlgorithm #MinimumSubarray #GeeksforGeeks #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
**Day 106 of #365DaysOfLeetCode Challenge** Today’s problem: **Number of Boomerangs (LeetCode 447)** A very interesting problem that combines **geometry + hashing**. 💡 **Core Idea:** A boomerang is defined as: 👉 `(i, j, k)` such that distance(i, j) == distance(i, k) ⚠️ Order matters → (i, j, k) ≠ (i, k, j) 📌 **Approach:** * Fix one point `i` as the center * Compute distance from `i` to every other point * Store frequencies of distances in a HashMap 👉 If `count` points have the same distance from `i`, then number of boomerangs = `count * (count - 1)` Why? Because order matters → permutations! ⚡ **Time Complexity:** O(n²) ⚡ **Space Complexity:** O(n) **What I learned today:** When order matters in combinations → think **permutations (n × (n-1))** 💭 **Key Takeaway:** * Fix one point → reduce problem complexity * Use hashing to group equal distances * Apply math on frequencies This is a great example of: 👉 Turning a geometric problem into a hashmap problem #LeetCode #DSA #HashMap #Geometry #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 82 — Kadane’s Algorithm (Maximum Subarray Sum with One Deletion) Pushing forward with a more advanced Kadane variation — today I solved a problem where you’re allowed to delete at most one element from the subarray to maximize the sum. 📌 Problem Solved: LeetCode 1186 – Maximum Subarray Sum with One Deletion 🧠 The Twist on Standard Kadane: We now need to track two states at each index: nd = maximum subarray sum ending at i with no deletion used so far. od = maximum subarray sum ending at i with exactly one deletion used so far. Transition logic: nd = Math.max(arr[i], nd + arr[i]) → classic Kadane (no deletion). od = Math.max(nd_prev, od_prev + arr[i]) → either skip deleting this element (so use previous no‑deletion state) or extend a previously deleted subarray. Why track both? Because at any point, the best subarray ending here may have never deleted, or may have deleted a previous element. The answer is the max of all nd and od across the array. 💡 Key Insight: Kadane’s pattern isn’t just one variable — it scales to multiple states. This “state‑based DP” approach is the bridge between Kadane and more complex subarray problems. No guilt about past breaks — just leveling up one variation at a time. #DSA #KadaneAlgorithm #MaximumSubarrayWithDeletion #LeetCode1186 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
✳️Day 35 of #100DaysOfCode✳️ 📌 Cracking the "Redundant Connection" Problem with DSU! 🛠️ My Approach: The DSU Strategy The Disjoint Set Union (or Union-Find) algorithm is perfect here because it allows us to track connected components efficiently as we iterate through the edges. ✨The Steps in my Code: 1️⃣Initialization: Created a parent array where every node is initially its own parent (representing n independent sets). 2️⃣Iterative Union: For every edge (u, v) in the input: Find the root (representative) of u. Find the root (representative) of v. Cycle Detection: * If find(u) == find(v), it means u and v are already part of the same connected component. Adding this edge would create a cycle. 🚩 Since the problem asks for the last edge that causes the cycle, I return this edge immediately. 3️⃣Union: If they are in different sets, I perform a union by setting the parent of one root to the other. 4️⃣Optimization: I used Path Compression in the find function to keep the tree flat, ensuring almost constant time complexity. 💡 When should you use DSU? 🔅DSU is a powerhouse for specific graph scenarios. Reach for it when: Cycle Detection: You need to check if adding an edge creates a cycle in an undirected graph. 🔅Connected Components: You need to count or manage groups of connected nodes dynamically. 🔅Minimum Spanning Trees: It’s the backbone of Kruskal’s Algorithm. Grid Problems: Identifying "islands" or connected regions in a 2D matrix. #DataStructures #Algorithms #LeetCode #Java #GraphTheory #CodingLife #SoftwareEngineering
To view or add a comment, sign in
-
-
📅 Date: April 25, 2026 Day 4 of my LeetCode Journey 🚀 ✅ Problem Solved: 9. Palindrome Number 🧠 Approach & Smart Solution: While it's easy to solve this by converting the integer to a string and reversing it, that takes extra memory! I opted for a highly optimized mathematical approach. I reversed the integer by peeling off its digits one by one using modulo and division, keeping the space complexity to an absolute minimum. • Pseudo-code: Handle edge cases: If the number is less than 0, it can't be a palindrome, so return false. Store the original number in a temporary variable for final comparison. Initialize a 'reverse' variable to 0. Loop while the number is greater than 0: Extract the last digit: digit = x % 10. Add it to the reversed number: reverse = (reverse * 10) + digit. Remove the last digit from the original number: x = x / 10. Finally, return true if the original number matches the reversed number. This math-based solution avoids expensive string conversions and runs instantly! ⏱️ Time Complexity: O(log₁₀(n)) (We only iterate through the digits of the number) 📦 Space Complexity: O(1) (Only using a few integer variables) 📊 Progress Update: • Streak: 3 Days 🔥 • Difficulty: Easy • Pattern: Math / Digit Extraction 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Choosing mathematical operations over string manipulations is a great way to optimize basic algorithms! 💡 #LeetCode #DSA #Math #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
Day 26 of my #30DayCodeChallenge: The Power of Local vs. Global Optima! The Problem: Maximum Subarray. Given an integer array, find the contiguous subarray with the largest sum. It sounds simple, but the challenge is handling the trade-offs between including negative numbers or starting fresh. The Logic: This solution utilizes Kadane's Algorithm, which is a masterclass in dynamic programming where we only care about two values at any given moment: 1. Local Maximum (f): At each index, we decide: "Is it better to add the current number to our existing streak, or should I just start a brand new streak from this number?" f = max(current_element, f + current_element 2. Global Maximum (ans): We keep a running record of the best "Local Maximum" we've seen so far. 3. Global Maximum (ans): We keep a running record of the best "Local Maximum" we've seen so far. The "Greedy" Choice: The core intuition is that if a previous subarray sum becomes negative, it will only decrease the sum of any future subarray. In that case, we "greedily" reset our starting point. Efficiency: Time Complexity: O(n) - We only pass through the array once. Space Complexity: O(1) - No extra arrays needed, just two variables. One step closer to mastery. Onward to Day 27! #Java #Algorithms #DataStructures #LeetCode #ProblemSolving #150 OfCode
To view or add a comment, sign in
-
-
🔍 LeetCode 399 (Day 46 of LeetCode Journey)– Evaluate Division | Graph + DFS Approach Today I solved an interesting problem that combines graphs + mathematics + DFS traversal. 💡 Problem Insight: We are given equations like: a / b = 2.0 b / c = 3.0 The goal is to evaluate queries such as: 👉 a / c = ? 🧠 Key Idea: Convert the equations into a weighted graph: Each variable → node Each division → weighted edge Example: a → b (2.0) b → a (0.5) Then use DFS traversal to find a path between variables and multiply weights along the way. ⚙️ Approach: ✔ Build adjacency list ✔ Add reciprocal edges ✔ Run DFS for each query ✔ Track visited nodes to avoid cycles 📈 Time Complexity: O(Q × (V + E)) ✨ What I Learned: Real-world problems can be modeled as graphs DFS is powerful beyond just traversal Importance of handling edge cases (missing variables) 💻 Implemented in Java with clean structure and recursion. #LeetCode #DataStructures #Algorithms #Java #GraphTheory #CodingInterview #Learning #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Another LeetCode Problem Solved: Palindrome Number! 🔗 Check out my solution: https://lnkd.in/dwDMqXXn 💡 Problem Overview Given an integer x, determine whether it is a palindrome — meaning it reads the same forward and backward. (LeetCode) Examples: ✔ 121 → Palindrome ❌ -121 → Not a palindrome ❌ 10 → Not a palindrome 🧠 My Approach (Digit Reversal) Instead of converting the number to a string, I used a mathematical approach: Extract digits using % 10 Reverse the number step by step Compare reversed number with original ⚙️ Key Learnings ✔ Strong understanding of number manipulation ✔ Importance of handling edge cases (negative numbers, trailing zeros) (leet-solution.com) ✔ Practicing clean and efficient logic ⏱️ Complexity • Time Complexity: O(log n) • Space Complexity: O(1) 🔥 Why this problem matters Even though it’s an “easy” problem, it builds: Logical thinking Problem-solving fundamentals Confidence for bigger challenges 🚀 Next Goal Move towards optimized approaches and medium-level problems to strengthen DSA skills. #LeetCode #DSA #Python #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development