本文共 1221 字,大约阅读时间需要 4 分钟。
根据先进先出原则实现交易,例如:
buy 100 share(s) at $20 eachbuy 20 share(s) at $24 eachbuy 200 share(s) at $36 eachsell 150 share(s) at $30 each
得出计算结果为940。
优先卖掉持有时间最长的。
直接使用ArrayList保存,卖出时从第一个开始即可。
当然也可以用队列做。
实现代码:
private Integer calculation(Listtransactions) { int result = 0; List t = new ArrayList<>(); for (String transaction : transactions) { if (!transaction.isEmpty()) { String[] ss = transaction.split(" "); t.add(ss[0] + "-" + ss[1] + "-" + ss[4].replace("$", "")); } } for (int i = 0; i < t.size(); i++) { if (t.get(i).startsWith("sell")) { int num = Integer.valueOf(t.get(i).split("-")[1]); int sellPrice = Integer.valueOf(t.get(i).split("-")[2]); for (int j = 0; j < i; j++) { String[] sss = t.get(j).split("-"); if (num <= Integer.valueOf(sss[1])) { result += num * (sellPrice - Integer.valueOf(sss[2])); break; } else { result += Integer.valueOf(sss[1]) * (sellPrice - Integer.valueOf(sss[2])); num -= Integer.valueOf(sss[1]); } } } } return result;}
转载地址:http://cbyi.baihongyu.com/