2592. Maximize Greatness of an Array - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

You are given an array of integers. You can reorder (or permute) the array arbitrarily. The “greatness” of an array is defined as the maximum number of disjoint pairs you can form such that in each pair one element is strictly smaller than the other. Equivalently, if you view the process as “matching” a smaller element with a larger element (using each element at most once), the greatness is the number of such valid pairs. Your task is to determine the maximum possible greatness that can be achieved by reordering the array.

Example 1

Input:

nums = [1, 3, 5, 2, 1, 3]

Output:

4

Explanation:

  1. Sort the array: [1, 1, 2, 3, 3, 5].
  2. Greedily pair elements by using two pointers:
    • Pair the first 1 with 2 (since 2 > 1).
    • Pair the second 1 with the first 3.
    • Pair the remaining 2 with the second 3.
    • Pair the first 3 with 5.
  3. Total valid pairs formed = 4.
    This is the maximum greatness.

Example 2

Input:

nums = [1, 2, 3, 4]

Output:

3

Explanation:

  • Sorted array: [1, 2, 3, 4].
  • The valid pairs can be (1,2), (2,3), (3,4).
  • Maximum greatness = 3.

Example 3

Input:

nums = [1, 1, 1, 1]

Output:

0

Explanation:

  • All elements are equal, so no element is strictly greater than another.
  • No valid pair can be formed.
  • Maximum greatness = 0.

Constraints

  • 1 ≤ nums.length ≤ 10⁵ (or similar scale)
  • The values in the array can be any integers (often non-negative, but the method works in general).

Hints

  1. Sorting Insight:
    Sorting the array will arrange the numbers in non-decreasing order. This helps in pairing the smallest available element with the next larger candidate.

  2. Greedy Pairing with Two Pointers:
    Use a two-pointer technique on the sorted array. One pointer (i) will track the current smallest element that you want to pair, while the other pointer (j) will search for a candidate that is strictly larger than it. Every time a valid pair is found, both pointers are advanced.

Approach 1: Brute Force

Explanation

A brute force solution might try every permutation of the array and count the number of valid pairs (where one element is paired with a strictly larger element). Then, take the maximum count over all permutations.

  • Drawbacks:
    • There are n! possible permutations, making this approach computationally infeasible for even moderately sized arrays.

This method is only useful for understanding the problem on a small scale.

Approach 2: Greedy Two-Pointer after Sorting (Optimal)

Explanation

  1. Sort the Array:
    Sorting arranges the elements in non-decreasing order.
  2. Initialize Two Pointers:
    • Pointer i starts at the beginning (index 0) and represents the element you want to match.
    • Pointer j also starts at the beginning and is used to find an element strictly greater than the one at pointer i.
  3. Greedy Matching:
    • Increment j until you find an element greater than nums[i].
    • When found, this forms a valid pair; increment the count and move pointer i to the next element to be paired.
    • Continue moving pointer j until the end of the array.
  4. Result:
    The count of valid pairs is the maximum “greatness” of the array.

Visual Walkthrough

Consider nums = [1, 3, 5, 2, 1, 3].

  1. Sort:
    Sorted array: [1, 1, 2, 3, 3, 5].
  2. Pairing Process:
    • i = 0 (value 1), j = 0 (value 1): Since 1 is not greater than 1, increment j.

    • j = 1 (value 1): Still not greater; increment j.

    • j = 2 (value 2): 2 > 1, so form a pair. Increment count (count = 1), move i to 1.

    • Now, i = 1 (value 1), j = 3 (value 3): 3 > 1, form a pair. Increment count (count = 2), move i to 2.

    • i = 2 (value 2), j = 4 (value 3): 3 > 2, form a pair. Increment count (count = 3), move i to 3.

    • i = 3 (value 3), j = 5 (value 5): 5 > 3, form a pair. Increment count (count = 4), move i to 4.

    • j reaches the end of the array.
      Maximum greatness = 4.

Complexity

  • Time Complexity: O(n log n) due to sorting and O(n) for the two-pointer pairing, totaling O(n log n).

  • Space Complexity: O(1) extra space (if sorting is done in-place).

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:
    • Sorting the array: O(n log n)
    • Two-pointer pairing: O(n)
    • Overall: O(n log n)
  • Space Complexity: O(1) extra space if sorting is done in-place.

Step-by-Step Walkthrough

  1. Sort the Array:
    Convert the unsorted array into a sorted one.
  2. Initialize Pointers:
    Start with both pointers at the beginning of the sorted array.
  3. Iterate and Pair:
    For each candidate element at pointer i, advance pointer j until you find an element that is strictly larger. Form the pair, increment the count, and move pointer i to look for the next pair.
  4. Terminate:
    Stop when pointer j reaches the end of the array. The count reflects the maximum number of pairs (i.e., the maximum greatness).

Common Mistakes and Edge Cases

  • Not Sorting:
    Failing to sort the array makes it impossible to efficiently form pairs.

  • Handling Duplicates:
    Duplicate values can only be paired if there is a strictly larger value available. Arrays with all identical elements yield greatness = 0.

  • Off-by-One Errors:
    Ensure that the pointers are advanced correctly without skipping potential pairs.

Alternative Variations

  • Different Pairing Conditions:
    If the problem required pairing with a non-strict inequality (e.g., greater than or equal), the logic would need to be adjusted.

  • Weighted Pairing:
    Variations might involve weights or costs associated with elements, changing the greedy strategy.

  • Maximizing Other Metrics:
    Instead of counting pairs, you could be asked to maximize the sum of differences, which would require a different pairing strategy.

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;