Today made a company T questions, which is a programming problem is the greedy algorithm to solve the problem, which is similar to the classic knapsack problem. Just before seen, written when the impression with 80% actually do it, and I feel very pleasant to record it.
The original title I do not remember, write a similar topic.
Knapsack problem is a combinatorial optimization problem is described as follows: given a fixed size, it is possible carrying weight W backpack and a set value of the weight of the article, to find an optimum solution such that the weight of items loaded package does not exceed W and a maximum total value.
1, problem analysis
Data: Item number n = 5, the weight of items weights = [2,2,6,5,4], the value of goods values = [6,3,5,4,6], the total capacity of the backpack W = 10.
2, thinking problems
* First calculate the price for each item, it is the weight / the value obtained for each cost item, deposit into an array, in accordance with the ascending order. After traversing the array, until the capacity of> = 0, increases the value of max.
* code show as below:
let price = [2,2,3,1,5,2]; // Price let nums = [2,3,1,5,4,3]; // number corresponding to let money = 6; // there how much tanxin (. price, the nums, money) function tanxin (. price, the nums, money) { // the return value to the let max = 0; // how much remains now the let endMoney = money; the let ARR = []; / / traversal price, the price, quantity, and proportion of a memory array into price.forEach ((ELE, IDX) => { arr.push ({ '. price':. price [IDX], 'NUM': the nums [IDX], 'Bili':. price [IDX] / the nums [IDX] }) }) // do some sort, from small to large arr.sort ((A, B) => { return a.bili - b.bili }) / / traverse the array of items ARR .forEach ((ele, idx) = > { // need to define when greater than 0, or will have been added to go IF (endMoney - ele.price> = 0) { // rest of the money to reduce endMoney = endMoney - ele.price; increase the maximum number of items you can buy // ele.num + = max } }) the console.log (max) }