🚀 Solved: Maximum Subarray Problem (Kadane’s Algorithm) Today, I solved the classic Maximum Subarray problem from LeetCode using an efficient approach. 🔍 Problem Statement Given an integer array, find the contiguous subarray with the largest sum and return that sum. 💡 Approach Used: Kadane’s Algorithm Instead of checking all possible subarrays (which would take O(N²)), I used an optimized linear approach: -> Keep a running sum of elements -> If the sum becomes negative, reset it to 0 -> Track the maximum sum encountered so far ⚡ Time Complexity: O(N) 📦 Space Complexity: O(1) 💻 Java Implementation: class Solution { public int maxSubArray(int[] nums) { int sum = 0; int max = nums[0]; for (int i = 0; i < nums.length; i++) { sum = sum + nums[i]; if (sum > max) { max = sum; } if (sum < 0) { sum = 0; } } return max; } } 🎯 Key Insight: Even if a running sum becomes negative, continuing it will only decrease future subarray sums—so it's better to restart. This problem is a great example of how understanding patterns can reduce complexity from brute force to optimal. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #SoftwareEngineering #ProblemSolving
Solved Maximum Subarray Problem with Kadane's Algorithm
More Relevant Posts
-
🚀 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 32 of #128DaysOfCode Today I explored an efficient way to find the square root of a number without using built-in functions. Instead of the usual brute force or binary search, I implemented Newton’s Method (Babylonian Method) — a powerful mathematical approach that converges very fast. 🔹 The idea is to continuously improve our guess using: r = (r + x / r) / 2 This method quickly narrows down to the correct integer square root, making it both optimized and elegant. 💡 Key Takeaways: - Learned how mathematical concepts can optimize coding problems - Understood the importance of avoiding overflow using "long" - Practiced writing clean and efficient Java code 🔥 Consistency is the real game changer. Step by step, improving logic and problem-solving skills! #Java #DSA #CodingJourney #ProblemSolving #Consistency #LearnInPublic
To view or add a comment, sign in
-
-
Ever tried to run a standard Gaussian blur and watched your processing time quadratically explode? 🐢📉 I just published a new tutorial on Baeldung detailing how to implement a highly optimized, Fast Gaussian Blur in Java. The traditional 2D convolution matrix gives us a time complexity of O(n * r²), which quickly becomes a bottleneck for high-res images or large blur radii. In this article, I break down how to drop that complexity down to a flat O(n) by leveraging two mathematical properties: 1️⃣ Separable Filters: Breaking a 2D matrix down into sequential horizontal and vertical 1D passes. 2️⃣ The Central Limit Theorem: Approximating a true Gaussian bell curve by applying a lightning-fast sliding-window Box Blur three times. The result? A blur effect where the processing time is completely independent of the blur radius. 🚀 You can read the full breakdown, analyze the math, and grab the JUnit 5 tested code here: [https://lnkd.in/d6NMwVjw] How do you usually handle expensive image processing tasks in your Java pipelines? Let me know below! 👇 #Java #Algorithms #SoftwareEngineering #ImageProcessing #Baeldung #PerformanceOptimization
To view or add a comment, sign in
-
🚀 LeetCode Problem of the Day 📌 Problem: Minimum Distance to Target Element Given an integer array nums (0-indexed) and two integers target and start, we need to find an index i such that: nums[i] == target |i - start| is minimized 👉 Return the minimum absolute distance. 💡 Key Idea: We simply scan the array and track the minimum distance whenever we find the target. 🧠 Approach Traverse the array Whenever nums[i] == target, compute abs(i - start) Keep updating the minimum result 💻 Java Solution class Solution { public int getMinDistance(int[] nums, int target, int start) { int res = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { res = Math.min(res, Math.abs(i - start)); } } return res; } } 📊 Complexity Analysis ⏱ Time Complexity: O(n) → single pass through the array 🧠 Space Complexity: O(1) → no extra space used ⚡ Simple linear scan, optimal solution — sometimes brute force is already the best solution! #LeetCode #Coding #Java #ProblemSolving #DataStructures #Algorithms #InterviewPrep
To view or add a comment, sign in
-
-
🚀 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 27 of #100DaysOfCode Solved Single Element in a Sorted Array 🔍 Today’s problem was a great mix of binary search + pattern observation. Instead of checking every element, I used index parity (even/odd) to eliminate half of the search space each time — achieving O(log n) time complexity ⚡ 🔍 Key Learnings: How sorted structure helps optimize search Using index parity to detect the correct half Writing clean edge-case handling for boundaries 💻 Implemented in Java with optimal approach 📈 Runtime: 0 ms | Beat 100% #DSAwithEdSlash #LeetCode #BinarySearch #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 24/100 — #100DaysOfLeetCode Another step forward in strengthening string problem-solving skills 💻🔥 ✅ Problem Solved: 🔹 LeetCode 28 — Find the Index of the First Occurrence in a String 💡 Concepts Used: String Matching Two Pointer / Brute Force Comparison 🧠 Key Learning: The task was to locate the first occurrence of a pattern (needle) inside another string (haystack). I practiced comparing characters sequentially and handling mismatches carefully while traversing the string. ⚡ Insight Gained: Even simple-looking problems help build a strong foundation for advanced string searching algorithms like KMP and Rabin–Karp. Understanding basic string matching logic is essential before moving to optimized pattern-search techniques. Consistency continues 🚀 #100DaysOfLeetCode #LeetCode #DSA #Strings #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Day 2 of my LeetCode Journey Today’s focus: Prefix Sum + HashMap - Problem Type: Counting “Good Subarrays” - Approach: Converted the problem into a prefix sum transformation Used a HashMap to track frequencies Optimized brute force (O(n²)) → O(n) Key Learning: The real trick isn’t coding — it’s recognizing how to transform the problem. Instead of checking every subarray, I tracked a derived value: prefix - (index + 1) and counted how many times it appeared before. That shift turns an impossible brute force into a clean linear solution. -Takeaway: Most DSA problems are not about new algorithms — they’re about seeing the hidden pattern faster. Building consistency, one day at a time. #LeetCode #Day2 #DSA #Java #ProblemSolving #Consistency #CodingJourney
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
-
✅ Solved: Anagram Palindrome Another step forward in sharpening problem-solving skills 🚀 🔍 Problem Insight: A string can be rearranged into a palindrome if at most one character has an odd frequency. Simple idea, but powerful when applied efficiently. 💡 Implemented using an optimized approach in Java: - Time Complexity: O(n) - Space Complexity: O(1) 📊 Result: ✔️ Test Cases Passed: 1113 / 1113 ✔️ Accuracy: 100% ✔️ Time Taken: 0.52s Small problem, but a good reminder that the right observation beats brute force every time ⚡ #DataStructures #Algorithms #Java #ProblemSolving #CodingJourney #DSA #TechGrowth
To view or add a comment, sign in
-
Explore related topics
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