LoginSignup
2
0

More than 3 years have passed since last update.

【python】所持金で購入できるおもちゃの最大個数を求めるプログラム

Posted at

【python】所持金で購入できるおもちゃの最大個数を求めるプログラム

自分用のメモです。

▼設問

  • 各おもちゃの価格が入ったlistが与えられる。
  • 所持金(k)で購入できるおもちゃの最大個数を求める。

URL

▼sample input

prices = [1,12,5,111,200,1000,10]
k=50

▼sample output

4

▼my answer

def maximumToys(prices, k):
    ans=total=0
    if min(prices) > k:
        return 0
    for price in sorted(prices):
        total += price
        if total <= k:
            ans+=1
    return ans

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
    nk = input().split()
    n = int(nk[0])
    k = int(nk[1])
    prices = list(map(int, input().rstrip().split()))
    result = maximumToys(prices, k)
    fptr.write(str(result) + '\n')
    fptr.close()



一個も買えないパターンも考慮。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0