博客
关于我
[随缘一题]实现交易计算盈利
阅读量: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实现intro sort内省排序算法(附完整源码)
查看>>
Objective-C实现inverse matrix逆矩阵算法(附完整源码)
查看>>
Objective-C实现inversions倒置算法(附完整源码)
查看>>
Objective-C实现isalpha函数功能(附完整源码)
查看>>
Objective-C实现islower函数功能(附完整源码)
查看>>
Objective-C实现isPowerOfTwo算法(附完整源码)
查看>>
Objective-C实现isupper函数功能(附完整源码)
查看>>
Objective-C实现ItemCF算法(附完整源码)
查看>>
Objective-C实现ItemCF算法(附完整源码)
查看>>
Objective-C实现iterating through submasks遍历子掩码算法(附完整源码)
查看>>
Objective-C实现iterative merge sort迭代归并排序算法(附完整源码)
查看>>
Objective-C实现jaccard similarity相似度无平方因子数算法(附完整源码)
查看>>
Objective-C实现Julia集算法(附完整源码)
查看>>
Objective-C实现k nearest neighbours k最近邻分类算法(附完整源码)
查看>>
Objective-C实现k-means clustering均值聚类算法(附完整源码)
查看>>
Objective-C实现k-Means算法(附完整源码)
查看>>
Objective-C实现k-nearest算法(附完整源码)
查看>>
Objective-C实现KadaneAlgo计算给定数组的最大连续子数组和算法(附完整源码)
查看>>
Objective-C实现kahns algorithm卡恩算法(附完整源码)
查看>>
Objective-C实现karatsuba大数相乘算法(附完整源码)
查看>>