MaxArrays

mail@pastecode.io avatar
unknown
python
5 months ago
941 B
3
Indexable
def getMaximumDistinctCount(a, b, k):
    # Count the frequency of elements in both arrays
    a_count = {}
    b_count = {}
    for i in range(len(a)):
        a_count[a[i]] = a_count.get(a[i], 0) + 1
        b_count[b[i]] = b_count.get(b[i], 0) + 1

    # Sort the counts in descending order
    a_sorted = sorted(a_count.items(), key=lambda x: x[1], reverse=True)
    b_sorted = sorted(b_count.items(), key=lambda x: x[1], reverse=True)

    # Perform the swaps
    i, j = 0, 0
    while k > 0 and i < len(a_sorted) and j < len(b_sorted):
        # Swap the elements if a[i] is smaller than b[j]
        if a_sorted[i][0] < b_sorted[j][0]:
            a_sorted[i] = (a_sorted[i][0], a_sorted[i][1] - 1)
            b_sorted[j] = (b_sorted[j][0], b_sorted[j][1] - 1)
            k -= 1
        else:
            i += 1

    # Count the distinct elements in the modified a array
    return len([count for count in a_sorted if count[1] > 0])
Leave a Comment