š 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
Kadane Algorithm with One Deletion for Maximum 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 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
-
-
Day 79/100 | #100DaysOfDSA š§©š Todayās problem: Flatten Binary Tree to Linked List A powerful tree transformation problem using pointer manipulation. Problem idea: Convert a binary tree into a linked list in-place following preorder traversal. Key idea: Iterative traversal + rewiring (similar to Morris traversal idea). Why? ⢠We need preorder sequence (Root ā Left ā Right) ⢠Instead of extra space, we modify pointers in-place ⢠Efficient and avoids recursion stack How it works: ⢠Traverse using a pointer curr ⢠If left child exists: ā Find rightmost node of left subtree ā Connect it to currentās right subtree ā Move left subtree to right ā Set left = null ⢠Move to next node (curr.right) Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Tree problems can often be optimized using in-place pointer rewiring, avoiding extra space. š„ This pattern is very useful for tree flattening and traversal optimizations. Day 79 done. š #100DaysOfCode #LeetCode #DSA #Algorithms #BinaryTree #MorrisTraversal #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
š LeetCode Challenge 28/50 š” Approach: Bidirectional HashMap + HashSet This is the word-level version of Isomorphic Strings! We need a true bijection ā each pattern letter maps to exactly one word AND each word maps to exactly one letter. One map alone isn't enough! š Key Insight: ā Split string s into words array ā If lengths differ ā instantly return false ā Map char ā word using HashMap ā Track already-used words with a HashSet ā If a new char tries to claim an already-used word ā false! š Complexity: ā Time: O(n) ā single pass through pattern ā Space: O(n) ā map + set storing at most n entries Pattern recognition in problem solving is just like pattern recognition in code ā once you see the structure, the solution follows naturally! š #LeetCode #DSA #HashMap #Java #ADA #PBL2 #LeetCodeChallenge #Day28of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #WordPattern
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
-
#70DayStreak š 27/04/26 ā Optimized Sliding Window | Longest Substring Without Repeating Characters (LeetCode 3) Today I revisited a classic problem ā Longest Substring Without Repeating Characters ā and implemented a more optimized Sliding Window using HashMap. Previously, I used a HashSet approach where the window shrinks step-by-step. This time, I upgraded it with a "jumping window" technique, allowing direct pointer movement. š Key Optimization Insight Instead of removing characters one by one: ⢠Store last seen index of each character ⢠When duplicate appears ā jump left pointer instantly ⢠Avoid unnecessary iterations š This reduces redundant work and improves efficiency significantly. āļø Algorithm Highlights ⢠Left pointer jumps using stored indices ⢠Right pointer scans once ⢠Continuous max window calculation š Complexity ⢠Time: O(n) ⢠Space: O(min(m, n)) š Performance ⢠Runtime: 5ms (Beats 87.15%) ⢠Memory: 45.67 MB (Beats 69.72%) š„ Consistency Metrics ⢠84 Active Days ⢠70-Day Streak š” Key Learning Switching from HashSet ā HashMap transforms the approach from iterative shrinking to direct optimization. This is a small shift in thinking, but a big upgrade in performance. š Even after 100+ problems, refinement and optimization still matter. #DSA #Java #LeetCode #SlidingWindow #HashMap #Algorithms #CodingJourney #ProblemSolving #Optimization #100DaysOfCode
To view or add a comment, sign in
-
-
š” Day 64 of LeetCode Problem Solved! š§ š 2033. Minimum Operations to Make a Uni-Value Grid š š Solution Code: https://lnkd.in/gts2KBqr š§ Approach: ⢠Flattened the 2D grid into a sorted 1D list. ⢠Chose the median as the target value ā it minimises total absolute deviation mathematically. ⢠Early-exit with -1 if any element has a different remainder mod x than the median. ⢠Summed |element - median| / x for all elements to get the answer. ā” Key Learning: ⢠The median is the optimal target for minimising sum of absolute differences ā a powerful mathematical insight that replaces brute-force enumeration entirely. ⢠A simple remainder check handles all impossible cases upfront. ā±ļø Complexity: ⢠Time: O(mĀ·nĀ·log(mĀ·n)) ⢠Space: O(mĀ·n) #LeetCode #Java #DSA #ProblemSolving #Consistency #CodingJourney #Algorithms #Grid
To view or add a comment, sign in
-
-
Day 55/75 ā Shortest Subarray with Sum at Least K Todayās problem was a challenging one involving prefix sums and a monotonic deque. Approach: ⢠Use prefix sum to convert subarray sum into difference of indices ⢠Maintain a deque to keep indices in increasing order of prefix sums ⢠Remove useless indices to keep it optimal Key logic: while (!dq.isEmpty() && ps[j] - ps[dq.peekFirst()] >= k) { minLen = Math.min(minLen, j - dq.pollFirst()); } while (!dq.isEmpty() && ps[j] <= ps[dq.peekLast()]) { dq.pollLast(); } dq.offerLast(j); Time Complexity: O(n) Space Complexity: O(n) A tough problem that builds strong intuition for prefix sums + deque optimization. 55/75 š #Day55 #DSA #PrefixSum #Deque #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
Day 102 of 365 Days of code I'm falling in love with graphs š·ļø Ever wondered how multi source bfs works "_". i thought we must be using some kind of concurrency or threading concepts to do perform bfs parallely at the same time. Then i saw some discussion from CF, and a guy said consider bfs search has multiple sources, each starting from a part of graph. A simple solution is to think about an imaginary node connecting all these multiple sources, and push the imaginary node into queue. Thereby you will be able simultaneously traverse the graph, where it looks like each of the node will be performed a bfs search, simultaneously. Instead of using an imaginary node, just push all the source nodes into the queue. and start performing bfs. both of the approaches are the same, we reach the second state after performing the first one, so instead of wasting time on constructing an imaginary node we directly enqueue the source nodes into the queue. SOrry for the bad english, i'm feeling sleepy :( Qn 1) Rotten oranges Approach: Multi Source Bfs Explanation: i wanna sleep bruv #365daysOfCode #NeetCodeĀ #leetcodeĀ #DSAĀ #python #LeetCode #ProblemSolvingĀ #Algorithms #365dayschallenge
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