# Here your code ! INF = 1 << 28 n = gets.to_i m = n.times.map { gets.to_i } S = 1 << n P = Array.new(S) dp = Array.new(S) P[0] = 0 dp[0] = 0 S.times do |s| n.times do |i| mask = 1 << i if s & mask == 0 P[s|mask] = ((P[s] + m[i]) % 1000) buy = P[s] > m[i] ? 0 : m[i] - P[s] sum = dp[s] + buy dp[s|mask] ||= sum dp[s|mask] = sum if sum < dp[s|mask] end end end puts dp[S-1]