Codepath

Performances With Maximum Audience

Unit 2 Session 1 (Click for link to problem statements)

U-nderstand

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

  • Q: What is the problem asking for?

    • A: The problem asks to return the combined audience size of all performances that have the maximum audience size from an array of audience sizes.
  • Q: What are the inputs?

    • A: An array audiences of positive integers representing audience sizes for different performances.
  • Q: What are the outputs?

    • A: An integer representing the combined audience size of all performances with the maximum audience size.
  • Q: Are there any constraints on the values in the array?

    • A: The values should be positive integers.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

Note: Like many interview questions, this problem can be solved multiple ways. If you chose to approach this without using a dictionary, check out the Performances-With-Maximum-Audience-II solution guide.

General Idea: Find the maximum audience size, then sum the audience sizes of all performances that match this maximum size.

1) Find the maximum value in the `audiences` array and store it in `max_audience`.
2) Initialize a dictionary `size_map` to count occurrences of each audience size.
3) Iterate through the `audiences` array.
   - For each audience size, update its count in `size_map`.
4) Multiply the count of `max_audience` in `size_map` by `max_audience` to get the combined audience size for performances with the maximum audience.
5) Return the combined audience size.

⚠️ Common Mistakes

  • Ensure that the max_audience is correctly identified.
  • Handle cases where the audiences array is empty by returning 0.

I-mplement

def max_audience_performances(audiences):
    if not audiences:
        return 0
    
    # Step 1: Find the maximum audience size
    max_audience = max(audiences)
    size_map = {}

    # Step 2: Count occurrences of each audience size
    for audience in audiences:
        if audience in size_map:
            size_map[audience] += 1
        else:
            size_map[audience] = 1

    # Step 3: Calculate combined audience size for performances with max audience size
    return size_map[max_audience] * max_audience
Fork me on GitHub