Skip to content

2012. Sum of Beauty in the Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int sumOfBeauties(vector<int>& nums) {
    const int n = nums.size();
    int ans = 0;
    vector<int> minOfRight(n);
    minOfRight.back() = nums.back();

    for (int i = n - 2; i >= 2; --i)
      minOfRight[i] = min(nums[i], minOfRight[i + 1]);

    int maxOfLeft = nums[0];

    for (int i = 1; i <= n - 2; ++i) {
      if (maxOfLeft < nums[i] && nums[i] < minOfRight[i + 1])
        ans += 2;
      else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1])
        ans += 1;
      maxOfLeft = max(maxOfLeft, nums[i]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int sumOfBeauties(int[] nums) {
    final int n = nums.length;
    int ans = 0;
    int[] minOfRight = new int[n];
    minOfRight[n - 1] = nums[n - 1];

    for (int i = n - 2; i >= 2; --i)
      minOfRight[i] = Math.min(nums[i], minOfRight[i + 1]);

    int maxOfLeft = nums[0];

    for (int i = 1; i <= n - 2; ++i) {
      if (maxOfLeft < nums[i] && nums[i] < minOfRight[i + 1])
        ans += 2;
      else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1])
        ans += 1;
      maxOfLeft = Math.max(maxOfLeft, nums[i]);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def sumOfBeauties(self, nums: List[int]) -> int:
    n = len(nums)
    ans = 0
    minOfRight = [0] * (n - 1) + [nums[-1]]

    for i in range(n - 2, 1, -1):
      minOfRight[i] = min(nums[i], minOfRight[i + 1])

    maxOfLeft = nums[0]

    for i in range(1, n - 1):
      if maxOfLeft < nums[i] < minOfRight[i + 1]:
        ans += 2
      elif nums[i - 1] < nums[i] < nums[i + 1]:
        ans += 1
      maxOfLeft = max(maxOfLeft, nums[i])

    return ans