python筆試模板

求找零 硬幣個數最小的組合

import sys

if __name__ == "__main__":
    line = sys.stdin.readline().strip()
    cost = int(line)
    if cost <= 0 or cost > 1024:
        print("error")

    money = 1024
    coins = [1, 4, 16, 64]

    target = money - cost
    # print(target)
    dp = [0 for i in range(target + 1)]
    for i in range(1, target + 1):
        c = sys.maxsize
        if i - 1 >= 0:
            c = min(c, dp[i-1] + 1)
        if i - 4 >= 0:
            c = min(c, dp[i-4] + 1)
        if i - 16 >= 0:
            c = min(c, dp[i - 16] + 1)
        if i - 64 >= 0:
            c = min(c, dp[i-64] + 1)
        dp[i] = c
    print(dp[-1])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章