LeetCode 918: Maximum Sum Circular Subarray Solution

Master LeetCode problem 918 (Maximum Sum Circular Subarray), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use the Kadane's algorithm to find the maximum subarray sum. However, since the subarray can be circular, we need to consider two cases:

  1. Maximum subarray sum without wrapping around.
  2. Maximum subarray sum with wrapping around.

For the first case, we can use the regular Kadane's algorithm. For the second case, we can find the minimum subarray sum and then subtract it from the total sum to get the maximum subarray sum with wrapping around.

Finally, we compare the two cases and return the maximum value.

  • Time complexity: O(n)
  • Space complexity: O(1)

Solution Code

class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int totalSum = 0;
        int maxSum = nums[0], minSum = nums[0];
        int curMax = 0, curMin = 0;
        
        for (int num : nums) {
            curMax = Math.max(curMax + num, num);
            maxSum = Math.max(maxSum, curMax);
            
            curMin = Math.min(curMin + num, num);
            minSum = Math.min(minSum, curMin);
            
            totalSum += num;
        }
        
        if (maxSum > 0) {
            return Math.max(maxSum, totalSum - minSum);
        }
        
        return maxSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 918 (Maximum Sum Circular Subarray)?

This page provides optimized solutions for LeetCode problem 918 (Maximum Sum Circular Subarray) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 918 (Maximum Sum Circular Subarray)?

The time complexity for LeetCode 918 (Maximum Sum Circular Subarray) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 918 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 918 in Java, C++, or Python.

Back to LeetCode Solutions