DEV Community

Dev Nirwal
Dev Nirwal

Posted on

Maximum Absolute Sum of Any Subarray LC - 1749

Question link on leetcode: Leetcode

Intuition

Maximum subarray sum: Kadane's algorithm

Approach

Take two sums, Max subarray sum and Min subarray sum.
Use Kadane's algorithm to find both.
In the last, compare the max sum and min absolute sum and return the max between them.

Complexity

  • Time complexity: O(N)

  • Space complexity: O(1)

Code

class Solution {
    public int maxAbsoluteSum(int[] nums) {
        int maxSum = Integer.MIN_VALUE;
        int minSum = Integer.MAX_VALUE;
        int currMax = 0;
        int currMin = 0;
        for(int num: nums){
            currMax +=num;
            currMin +=num;
            maxSum = Math.max(maxSum,currMax);
            minSum = Math.min(minSum,currMin);
            if(currMax<0) currMax = 0;
            if(currMin>0) currMin = 0;
        }
        return Math.max(maxSum,Math.abs(minSum));
    }
}
Enter fullscreen mode Exit fullscreen mode

GitHub repo for more solutions: Git

Leetcode profile: Leetcode: devn007

Geeks for geeks profile: GFG: devnirwal16

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more