博客
关于我
[随缘一题]实现交易计算盈利
阅读量:190 次
发布时间:2019-02-28

本文共 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(List
transactions) { 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/

你可能感兴趣的文章
Objective-C实现connected components连通分量算法(附完整源码)
查看>>
Objective-C实现Connected Components连通分量算法(附完整源码)
查看>>
Objective-C实现Convex hull凸包问题算法(附完整源码)
查看>>
Objective-C实现convolution neural network卷积神经网络算法(附完整源码)
查看>>
Objective-C实现convolve卷积算法(附完整源码)
查看>>
Objective-C实现coulombs law库仑定律算法(附完整源码)
查看>>
Objective-C实现counting sort计数排序算法(附完整源码)
查看>>
Objective-C实现countSetBits设置位的数量算法(附完整源码)
查看>>
Objective-C实现currency converter货币换算算法(附完整源码)
查看>>
Objective-C实现cycle sort循环排序算法(附完整源码)
查看>>
Objective-C实现data transformations数据转换算法(附完整源码)
查看>>
Objective-C实现datamatrix二维码识别 (附完整源码)
查看>>
Objective-C实现DateToDay 方法算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>
Objective-C实现DBSCAN聚类算法(附完整源码)
查看>>
Objective-C实现decision tree决策树算法(附完整源码)
查看>>
Objective-C实现degreeToRadian度到弧度算法(附完整源码)
查看>>
Objective-C实现depth first search深度优先搜索算法(附完整源码)
查看>>
Objective-C实现DES和3DES加解密算法(附完整源码)
查看>>
Objective-C实现des文件加密算法(附完整源码)
查看>>