def balance(instances_by_az, number):
    """
    Tries to balance given AZs
    using given number of instances.
    Once they are balanced,
    returns the fill layout
    and the remained number of instances
    """
    az_count = len(instances_by_az)
    result = [0] * az_count
    from_min_to_max = sorted(zip(instances_by_az, range(0, az_count)), key=
        lambda x: x[0])
    reminder = number
    for x in range(0, az_count - 1):
        depth = from_min_to_max[x + 1][0] - from_min_to_max[x][0]
        number_needed = (x + 1) * depth
        if reminder > number_needed:
            reminder -= number_needed
            for y in range(0, x + 1):
                result[from_min_to_max[y][1]] += depth
        else:
            actual_depth = reminder / (x + 1)
            actual_reminder = reminder % (x + 1)
            for y in range(0, x + 1):
                result[from_min_to_max[y][1]
                    ] += y < actual_reminder and actual_depth + 1 or actual_depth
            reminder = 0
    return result, reminder
