hello-algo/codes/swift/chapter_greedy/coin_change_greedy.swift
nuomi1 8d5e84f70a
Feature/chapter greedy swift (#720)
* feat: add Swift codes for greedy_algorithm article

* feat: add Swift codes for fractional_knapsack_problem article

* feat: add Swift codes for max_capacity_problem article

* feat: add Swift codes for max_product_cutting_problem article
2023-09-03 19:09:45 +08:00

54 lines
1.7 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: coin_change_greedy.swift
* Created Time: 2023-09-03
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
// coins
var i = coins.count - 1
var count = 0
var amt = amt
//
while amt > 0 {
//
while i > 0 && coins[i] > amt {
i -= 1
}
// coins[i]
amt -= coins[i]
count += 1
}
// -1
return amt == 0 ? count : -1
}
@main
enum CoinChangeGreedy {
/* Driver Code */
static func main() {
//
var coins = [1, 5, 10, 20, 50, 100]
var amt = 186
var res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
//
coins = [1, 20, 50]
amt = 60
res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
print("实际上需要的最少数量为 3 ,即 20 + 20 + 20")
//
coins = [1, 49, 50]
amt = 98
res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
print("实际上需要的最少数量为 2 ,即 49 + 49")
}
}