#907. Sum of Subarray Minimums

ยท

1 min read

https://leetcode.com/problems/sum-of-subarray-minimums/description/?envType=daily-question&envId=2024-01-20


var sumSubarrayMins = function (arr) {
    const MOD = 1e9 + 7;
    const stack = [];
    let totalSum = 0;

    for (let currentIndex = 0; currentIndex <= arr.length; currentIndex++) {
        while (
            stack.length > 0
            && (
                currentIndex === arr.length
                || arr[stack[stack.length - 1]] > arr[currentIndex]) //previous element in arr is greater than current element
        ) {
            const poppedIndex = stack.pop();

            const leftBoundary = stack.length > 0 ? stack[stack.length - 1] : -1;
            //if there are indices in stack, return the last one,else return -1

            totalSum = (
                totalSum + arr[poppedIndex] //add sum to previous element 
                * (currentIndex - poppedIndex) //multiply  by difernce between the current index and the previous one in the arr
                * (poppedIndex - leftBoundary) //multiply by the differnce between the left boundary
                ) % MOD; //mod it according to the question because the value might be too large
        }

        stack.push(currentIndex); //push current index so that the process continues until there are no elements in arr
    }

    return totalSum;
};

This is a tough one. I solved this using Chatgpt but I need to solve more question like this to fully understand this sort of questions.

Even Needcode's explanation was becoming boring to at a point. Like someone said, it should be considered a hard question.

ย