博客
关于我
[随缘一题]实现交易计算盈利
阅读量: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/

你可能感兴趣的文章
Python 操作Redis
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(一)
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(二)
查看>>
Python 操作数据库
查看>>
Python 数据分析与可视化实战
查看>>
python 数据可视化 -- matplotlib02
查看>>
python 数据可视化利器
查看>>
Python 数据可视化详解
查看>>
python 数据库查询返回list或tuple
查看>>
Python 数据库连接池管理的基本知识 (附Demo)
查看>>
Python学习记录-2016-12-17
查看>>
Python 数据库骚操作 -- MySQL
查看>>
Python 数据操作详解
查看>>
Python 数据文件与网络数据序列化存储详解
查看>>
Python 数据结构与算法详解
查看>>
Python 数据采集、清洗、整理、分析以及可视化实战
查看>>
Python 数据预处理
查看>>
python 文件类型检测 linux和windows都可以用
查看>>
Python多处理池,加入;不等待继续?
查看>>
Python多处理帮助在条件下退出
查看>>