you have a vector of pair for each type { price , beauty } sorted in ascending order try the first fountain to be v[i] with price p1 and you have coins-p1 left the second one will be from range [ 0 , min(i-1, upper_bound(coins-p1)-1 ) ] now take the one with max beaut...