Traverse from the back of map so as to take bigger elements first
for u in list ( count . keys ( ) ) [ : : - 1 ] : NEW_LINE INDENT j = u NEW_LINE x = j * count [ j ] NEW_LINE if ( d <= x ) : NEW_LINE INDENT k += ( d + j - 1 ) // j NEW_LINE break NEW_LINE DEDENT k += count [ j ] NEW_LINE d -= x NEW_LINE DEDENT