{x}
blog image

Maximize the Beauty of the Garden

Solution Explanation: Maximize the Beauty of the Garden

This problem asks us to find the maximum beauty of a valid garden. A valid garden must have at least two flowers, and the first and last flowers must have the same beauty value. We can remove any number of flowers to achieve this.

The optimal solution leverages a hash table and prefix sums for efficient computation.

Algorithm:

  1. Initialization:

    • Create a hash table d to store the index of the first occurrence of each flower beauty value.
    • Create a prefix sum array s. s[i] will store the sum of the beauty values (considering only non-negative values) from index 0 to i-1. We use max(v,0) because negative beauty values decrease the total beauty, so we ignore them in the prefix sum calculation.
    • Initialize the maximum beauty ans to negative infinity.
  2. Iteration:

    • Iterate through the flowers array.
    • For each flower with beauty value v at index i:
      • Check for existing value: If v is already in d (meaning we've seen this beauty value before), it means we can potentially form a valid garden.
        • Calculate the beauty of the garden using the prefix sum: s[i] - s[d[v] + 1] + v * 2. This subtracts the sum of beauty values between the two occurrences of v and adds v*2 to account for the first and last flowers.
        • Update ans with the maximum beauty found so far.
      • Record first occurrence: If v is not in d, add it to d with its index i.
      • Update prefix sum: Update s[i+1] by adding max(v, 0) to s[i].
  3. Return: Return ans.

Time Complexity: O(n), where n is the number of flowers. We iterate through the array once. Hash table lookups and insertions are on average O(1).

Space Complexity: O(n) in the worst case, to store the hash table d if all flower beauty values are unique. The prefix sum array s also takes O(n) space.

Code Examples (Python):

import sys
from typing import List
 
class Solution:
    def maximumBeauty(self, flowers: List[int]) -> int:
        s = [0] * (len(flowers) + 1)
        d = {}
        ans = -sys.maxsize # Use -sys.maxsize for negative infinity
 
        for i, v in enumerate(flowers):
            if v in d:
                ans = max(ans, s[i] - s[d[v] + 1] + v * 2)
            else:
                d[v] = i
            s[i + 1] = s[i] + max(v, 0)
        return ans
 

The other languages (Java, C++, Go, TypeScript, Rust) follow a very similar structure, adapting the syntax and data structures appropriately. The core logic of using a hash table and prefix sum remains the same. The key difference might be in how negative infinity is represented in different languages (e.g., Integer.MIN_VALUE in Java, -sys.maxsize in Python, math.MinInt32 in Go).