def find_max_conflicts(conflicting_ids, cm, id_to_pr):
    """Return region ID of the region involved in the most conflicts

    conflicting_ids -- list of PairedRegion IDs
    cm -- ConflictMatrix object
    id_to_pr -- dict of {region ID: PairedRegion}. Result of 
        PairedRegions.byId() method.

    This methods returns the region ID (out of conflicting_ids) involved
        in the most conflicts. If there is a single region with the most
        conflicts, return it. Otherwise compare all regions with the 
        max number of conflicts on their gain. Gain is the length of
        the region minus the cumulative length of all of its conflicting
        regions. Return the one with the minimum gain. If both properties
        are equal, return the region that starts closest to the 3' end.
    """
    number_of_conflicts = {}
    for pr_id in conflicting_ids:
        noc = len(cm.conflictsOf(pr_id))
        if noc not in number_of_conflicts:
            number_of_conflicts[noc] = []
        number_of_conflicts[noc].append(pr_id)
    max_noc = max(number_of_conflicts.keys())
    max_ids = number_of_conflicts[max_noc]
    if len(max_ids) == 1:
        return max_ids[0]
    else:
        len_diffs = {}
        for pr_id in max_ids:
            pr_len = id_to_pr[pr_id].Length
            conf_len = sum([id_to_pr[i].Length for i in cm.conflictsOf(pr_id)])
            diff = pr_len - conf_len
            if diff not in len_diffs:
                len_diffs[diff] = []
            len_diffs[diff].append(pr_id)
        min_ld = min(len_diffs.keys())
        min_ids = len_diffs[min_ld]
        if len(min_ids) == 1:
            return min_ids[0]
        else:
            start_vals = {}
            for pr_id in min_ids:
                start = id_to_pr[pr_id].Start
                start_vals[start] = pr_id
            max_start = max(start_vals.keys())
            return start_vals[max_start]