LeetCode 2012: Sum of Beauty in the Array Solution

Master LeetCode problem 2012 (Sum of Beauty in the Array), 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.

2012. Sum of Beauty in the Array

Medium

Problem Explanation

Explanation:

To solve this problem, we iterate over each element in the array from index 1 to nums.length - 2. For each element nums[i], we check if it satisfies the conditions for beauty being 2, 1, or 0 as described in the problem statement. We maintain two arrays leftMax and rightMin to keep track of the maximum element to the left of nums[i] and the minimum element to the right of nums[i] respectively. By using these arrays, we can efficiently determine the beauty of each element.

  • If nums[i] is greater than leftMax[i] and less than rightMin[i], then the beauty is 2.
  • If nums[i] is greater than nums[i-1] and less than nums[i+1], then the beauty is 1.
  • Otherwise, the beauty is 0.

Finally, we sum up all the beauty values to get the total sum of beauty in the array. :

Solution Code

class Solution {
    public int sumOfBeauties(int[] nums) {
        int n = nums.length;
        int[] leftMax = new int[n];
        int[] rightMin = new int[n];
        leftMax[0] = nums[0];
        rightMin[n-1] = nums[n-1];
        
        for (int i = 1; i < n; i++) {
            leftMax[i] = Math.max(leftMax[i-1], nums[i]);
        }
        
        for (int i = n-2; i >= 0; i--) {
            rightMin[i] = Math.min(rightMin[i+1], nums[i]);
        }
        
        int sum = 0;
        for (int i = 1; i < n-1; i++) {
            if (nums[i] > leftMax[i-1] && nums[i] < rightMin[i+1]) {
                sum += 2;
            } else if (nums[i] > nums[i-1] && nums[i] < nums[i+1]) {
                sum += 1;
            }
        }
        
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2012 (Sum of Beauty in the Array)?

This page provides optimized solutions for LeetCode problem 2012 (Sum of Beauty in the Array) 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 2012 (Sum of Beauty in the Array)?

The time complexity for LeetCode 2012 (Sum of Beauty in the Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2012 on DevExCode?

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

Back to LeetCode Solutions