Skip to main content

Command Palette

Search for a command to run...

sumSubarrayMins

Published
1 min readView as Markdown
class Solution {
    public int sumSubarrayMins(int[] arr) {
        int MOD = 1_000_000_007;
        int n = arr.length;
        int[] left = new int[n];
        int[] right = new int[n];

        Stack<Integer> stack = new Stack<>();

        // Previous Less Element
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
                stack.pop();
            }
            left[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(i);
        }

        stack.clear();

        // Next Less or Equal Element
        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
                stack.pop();
            }
            right[i] = stack.isEmpty() ? n : stack.peek();
            stack.push(i);
        }

        // Final Result
        long result = 0;

        for (int i = 0; i < n; i++) {
            int leftCount = i - left[i] - 1;
            int rightCount = right[i] - i;

            // Convert to long before multiplication to avoid overflow
            long part1 = ((long) arr[i] * leftCount % MOD) * rightCount % MOD;
            long part2 = ((long) arr[i] * rightCount) % MOD;

            long contribution = (part1 + part2) % MOD;
            result = (result + contribution) % MOD;
        }

        return (int) result;
    }
}

More from this blog

Amit singh's blog

235 posts