import math


def downsampled_image_dims_from_desired_num_pixels(image_dims, num_pixels, maximum=False):
    """
    Compute the best downsampled image dimensions, given original image dimensions and the ideal total number of
    pixels for the downsampled image. The final number of pixels in the downsampled image dimensions may not be exact,
    but will best balance aspect ratio preservation and total number of pixels.  
    
    :param image_dims: The image dimensions of the original image.
    :type image_dims: sequence of ints.
    :param num_pixels: The ideal numbr of pixels in the downsampled image.
    :type num_pixels: int
    :param maximum: Whether the number of pixels is a hard maximum. Default is False.
    :type maximum: bool, optional
    :return: The image dimensions for a new downsampled image.
    """
    int_method = math.floor if maximum else round
    ratio = image_dims[1] / image_dims[0]
    new_dim_0 = (num_pixels / ratio) ** 0.5
    new_dim_1 = int_method(new_dim_0 * ratio)
    new_dim_0 = int_method(new_dim_0)
    new_img_dims = [new_dim_0, new_dim_1]
    num_pixels = new_dim_0 * new_dim_1
    return new_img_dims, num_pixels