LeetCode 1856: Maximum Subarray Min-Product Solution

Master LeetCode problem 1856 (Maximum Subarray Min-Product), 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.

1856. Maximum Subarray Min-Product

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and for each element, we find the left and right boundaries of the subarray with the minimum value equal to the current element. We calculate the sum of elements within this subarray and update the maximum min-product accordingly. This approach ensures that we consider all possible subarrays with the minimum value at the current element.

Time complexity: O(N) where N is the number of elements in the array. Space complexity: O(N) for storing the left and right boundaries.

Solution Code

class Solution {
    public int maxSumMinProduct(int[] nums) {
        long[] prefixSum = new long[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }

        Stack<Integer> stack = new Stack<>();
        long[] left = new long[nums.length];
        long[] right = new long[nums.length];
        for (int i = 0; i < nums.length; i++) {
            while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
                stack.pop();
            }
            left[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(i);
        }

        stack.clear();
        for (int i = nums.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
                stack.pop();
            }
            right[i] = stack.isEmpty() ? nums.length : stack.peek();
            stack.push(i);
        }

        long maxProduct = 0;
        for (int i = 0; i < nums.length; i++) {
            long sum = prefixSum[(int) right[i]] - prefixSum[(int) left[i] + 1];
            maxProduct = Math.max(maxProduct, nums[i] * sum);
        }

        return (int) (maxProduct % 1000000007);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1856 (Maximum Subarray Min-Product)?

This page provides optimized solutions for LeetCode problem 1856 (Maximum Subarray Min-Product) 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 1856 (Maximum Subarray Min-Product)?

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

Can I run code for LeetCode 1856 on DevExCode?

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

Back to LeetCode Solutions