1. A method comprising: by a computing device, accessing a plurality of image elements that have an ordered sequence; by the computing device, determining a plurality of clusters of the image elements, each of the clusters comprising one or more of the image elements arranged in a line, the image elements within each cluster being scaled to have a substantially same first dimension while maintaining their original aspect ratios and being arranged to maintain the ordered sequence, and each of the clusters having a substantially same second dimension; by the computing device, determining a cost for each of the clusters, wherein the cost for a cluster is based at least in part on a sum of costs for each image element in the cluster, the cost for a particular image element in the cluster being based at least in part on an affinity coefficient between a user node and another social-graph node in a social graph of a social-networking system, wherein the user node represents a user to whom the image elements are to be displayed, the another social-graph node is associated with a concept or another user associated with the particular image element, the affinity coefficient is based at least in part on a strength of a relationship between the user and the concept or the another user, and the affinity coefficient comprises a decay factor that causes the affinity coefficient to decrease with time; by the computing device, accessing a graph based on the clusters that maintains the ordered sequence, the graph comprising a plurality of paths, each path representing a layout of the image elements and having a total cost based on the costs of the clusters along the path; and by the computing device, identifying a path with a lowest total cost to determine a preferred one of the layouts.