Skip to content

Balanced Art Collection

LeWiz24 edited this page Aug 13, 2024 · 2 revisions

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
      • To find the length of the longest balanced subsequence where the difference between the maximum and minimum value is exactly 1.
    • What input is provided?
      • An integer array art_pieces.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Count the frequency of each number, then find the longest subsequence where the difference between the maximum and minimum value is exactly 1.

1) Use `Counter` to count the frequency of each number in `art_pieces`.
2) Initialize `max_length` to 0.
3) Iterate through each unique number in the array:
   - If `num + 1` exists, calculate the length of the balanced subsequence involving `num` and `num + 1`.
   - Update `max_length` if the current balanced subsequence is longer.
4) Return `max_length`.

⚠️ Common Mistakes

  • Not checking if num + 1 exists before calculating the balanced subsequence.

I-mplement

from collections import Counter

def find_balanced_subsequence(art_pieces):
    num_count = Counter(art_pieces)
    max_length = 0

    # Iterate through each unique number in the array
    for num in num_count:
        if num + 1 in num_count:
            # Check the length of the balanced subsequence involving 'num' and 'num + 1'
            current_length = num_count[num] + num_count[num + 1]
            max_length = max(max_length, current_length)
    
    return max_length
Clone this wiki locally