LeetCode 2832: Maximal Range That Each Element Is Maximum in It Solution

Master LeetCode problem 2832 (Maximal Range That Each Element Is Maximum in It), 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.

2832. Maximal Range That Each Element Is Maximum in It

Problem Explanation

Explanation:

The problem asks us to find the maximal range for each element in an array, where the element is the maximum value in that range. We can achieve this by iterating through the array and for each element, finding the range of indices where it is the maximum value.

To solve this problem, we can use two arrays left and right to store the leftmost and rightmost indices where the current element is the maximum value respectively. Then, we can compute the range for each element by calculating right[i] - left[i] + 1 where i is the index of the element. Solution:

Solution Code

class Solution {
    public int[] maxRange(int[] nums) {
        int n = nums.length;
        int[] left = new int[n];
        int[] right = new int[n];
        
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[i] >= nums[stack.peek()]) {
                stack.pop();
            }
            left[i] = stack.isEmpty() ? 0 : stack.peek() + 1;
            stack.push(i);
        }
        
        stack.clear();
        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
                stack.pop();
            }
            right[i] = stack.isEmpty() ? n - 1 : stack.peek() - 1;
            stack.push(i);
        }
        
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = right[i] - left[i] + 1;
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2832 (Maximal Range That Each Element Is Maximum in It)?

This page provides optimized solutions for LeetCode problem 2832 (Maximal Range That Each Element Is Maximum in It) 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 2832 (Maximal Range That Each Element Is Maximum in It)?

The time complexity for LeetCode 2832 (Maximal Range That Each Element Is Maximum in It) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2832 on DevExCode?

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

Back to LeetCode Solutions