#2012

Sum of Beauty in the Array

Medium
ArrayPrefix SumSuffix ArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

By using prefix and suffix arrays, we can efficiently determine the maximum values before and after each index, allowing us to compute the beauty in linear time.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a prefix array to store the maximum value from the start to each index.
  2. 2Step 2: Create a suffix array to store the maximum value from each index to the end.
  3. 3Step 3: Loop through each index 'i' from 1 to nums.length - 2.
  4. 4Step 4: For each 'i', check if nums[i] is greater than the prefix[i-1] and less than the suffix[i+1] for beauty 2.
  5. 5Step 5: If the above condition is not satisfied, check if nums[i-1] < nums[i] < nums[i+1] for beauty 1.
  6. 6Step 6: Sum the beauties and return the total.
solution.py19 lines
1def sumOfBeauty(nums):
2    n = len(nums)
3    prefix = [0] * n
4    suffix = [0] * n
5    prefix[0] = nums[0]
6    for i in range(1, n):
7        prefix[i] = max(prefix[i - 1], nums[i])
8    suffix[n - 1] = nums[n - 1]
9    for i in range(n - 2, -1, -1):
10        suffix[i] = max(suffix[i + 1], nums[i])
11    total_beauty = 0
12    for i in range(1, n - 1):
13        beauty = 0
14        if prefix[i - 1] < nums[i] < suffix[i + 1]:
15            beauty = 2
16        elif nums[i - 1] < nums[i] < nums[i + 1]:
17            beauty = 1
18        total_beauty += beauty
19    return total_beauty

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (once for prefix, once for suffix, and once for beauty calculation). The space complexity is O(n) due to the additional prefix and suffix arrays.

  • 1Using prefix and suffix arrays can significantly reduce the time complexity.
  • 2Understanding the conditions for beauty helps in optimizing checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.