MCPcopy Create free account
hub / github.com/course-dasheng/fe-algorithm / getMoney1

Function getMoney1

interview/coins.js:33–66  ·  view source on GitHub ↗
( number,option={})

Source from the content-addressed store, hash-verified

31
32// limit可以限制硬币的数量,比如{5000:0,1000:4,}就是没有5000的,1000的有四个
33var getMoney1 = function( number,option={}) {
34 if(!number){
35 return 0;
36 }
37 const coins = [5000,1000,500,100,50]
38 const obj = coins.reduce((ret,a)=>{
39 ret[a] = 0
40 return ret
41 },{})
42
43 let dp = Array(number+1).fill(Infinity)
44 dp[0] = 0
45 let selected = Array(number+1)
46 selected[0] = {...obj}
47 const limit = {...obj,...option}
48 for(const coin of coins){
49 let count = limit[coin]
50 for(let i=number;i>=0;i--){
51 if(dp[i]!==Infinity){
52 // 编译count, 钱数没超过number
53 for(let j=1;j<=count &&i+j*coin<=number;j++){
54 // 比如dp[100],2块的硬币有3个
55 // 遍历这三个硬币,可以从dp[98]+1, dp[96]+2,dp[94]+3 三个最小值决定
56 if(dp[i]+j<dp[i+j*coin]){
57 dp[i+j*coin] = dp[i]+j
58 selected[i+j*coin] = {...selected[i]}
59 selected[i+j*coin][coin]+=j
60 }
61 }
62 }
63 }
64 }
65 return dp[number]===Infinity?-1:selected[number]
66}
67console.log(getMoney(6200))
68
69const option = { 5000:0,1000:7,100:5}

Callers 1

coins.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected