如:
资金: 10000
基金:2种
价格 年收益
基金1 4000 400
基金2 3000 250
计算最佳收益
输入 资金 基金数 基金1价格 基金1年收益 基金2价格 基金2年收益 ...
输出购买方案和最佳收益
function GreatestReturnSolution(m, y, num, bonds)
if num == 1 then
local buy = math.floor(m/bonds[1][1]);
return {buy*bonds[1][2] * y, buy}
end
local bestbuy = 0;
local bestreturn = {0};
local idx = 0;
while(idx * bonds[num][1] < m) do
local ret = GreatestReturnSolution(m - idx*bonds[num][1], y, num-1,bonds)
if idx*bonds[num][2] + ret[1] > bestreturn[1] then
bestreturn = ret
bestreturn[1] = idx*bonds[num][2] + ret[1]
bestreturn[num + 1] = idx
end
idx = idx + 1
end
return bestreturn;
end
print("Input money: ")
money = 10000 --io.read();
print("Input years: ")
years = 1 --io.read();
print("Input bond count: ")
num = 2--io.read();
bond = {
{4000, 400},
{3000, 250}
}
--[[for i=1, num do
print("Input bond prize and return: ")
local p = io.read()
local r = io.read()
bond[i] = {p, r}
end --]]
function printinput()
print("---------------------")
print("money: "..money.."\tyears: "..years)
print("bond count:"..num)
for i=1, num do
print(bond[i][1].."\t"..bond[i][2])
end
print("---------------------")
end
printinput();
suo = GreatestReturnSolution(money, years, num, bond)
print("Best return: "..suo[1])
for i=2,#suo do
print(suo[i].." ")
end