Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1788. Maximize the Beauty of the Garden

Explanation

The problem asks us to find the maximum beauty of a garden by rearranging its flowers. The beauty of the garden is calculated as the sum of the beauty of its flowers multiplied by their positions. We need to rearrange the flowers in such a way that the beauty is maximized.

To solve this problem, we can follow the following approach:

  1. Calculate the initial beauty of the garden.
  2. Iterate over all possible pairs of flowers and calculate the beauty if we swap these two flowers.
  3. Update the maximum beauty if the new beauty after swapping is greater.
  4. Repeat step 2 and 3 until we have considered all possible pairs.

The time complexity of this approach is O(N^2) where N is the number of flowers in the garden. The space complexity is O(1) as we are not using any extra space.

class Solution {
    public int maxBeauty(int[] flowers) {
        int n = flowers.length;
        int maxBeauty = Integer.MIN_VALUE;
        
        int initialBeauty = 0;
        for (int i = 0; i < n; i++) {
            initialBeauty += flowers[i];
            if (i > 0) {
                initialBeauty -= Math.max(0, flowers[i] - flowers[i - 1]);
            }
        }
        
        maxBeauty = Math.max(maxBeauty, initialBeauty);
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int newBeauty = initialBeauty;
                if (j > i + 1) {
                    newBeauty -= Math.max(0, flowers[j] - flowers[j - 1]);
                }
                if (j < n - 1) {
                    newBeauty -= Math.max(0, flowers[j + 1] - flowers[j]);
                }
                newBeauty += Math.max(0, flowers[j] - flowers[i]);
                
                maxBeauty = Math.max(maxBeauty, newBeauty);
            }
        }
        
        return maxBeauty;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.