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

本文共 1618 字,大约阅读时间需要 5 分钟。

来源:

根据先进先出原则实现交易.

例如:

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保存,卖出时从第一个开始即可.

当然也可以用队列做.

实现代码

/** * calculation the result * @param transactions * @return */private Integer calculation(List
transactions) { int result = 0; //make the input to sell-100-20 format List
t = new ArrayList<>(); for (String transaction : transactions) { if ("".equals(transaction)) { continue; } String[] ss = transaction.split(" "); t.add(ss[0] + "-" + ss[1] + "-" + ss[4].replace("$", "")); } for (int i = 0; i < t.size(); i++) { //cal while sell if (t.get(i).startsWith("sell")) { //get the num and the sell price int num = Integer.valueOf(t.get(i).split("-")[1]); int sellPrice = Integer.valueOf(t.get(i).split("-")[2]); //cal the buy before sell for (int j = 0; j < i; j++) { //sell shares, use FIFO. String[] sss = t.get(j).split("-"); //if sell num < buy num, cal sell num shares in that transcation. if (num <= Integer.valueOf(sss[1])) { result += num * (sellPrice - Integer.valueOf(sss[2])); break; } else { //if sell num > buy num, cal all shares ,and cal new sellnum. result += Integer.valueOf(sss[1]) * (sellPrice - Integer.valueOf(sss[2])); num -= Integer.valueOf(sss[1]); } } } } return result;}

完。

ChangeLog

2019-02-24 完成

以上皆为个人所思所得,如有错误欢迎评论区指正。

欢迎转载,烦请署名并保留原文链接。

联系邮箱:huyanshi2580@gmail.com

更多学习笔记见个人博客------>

你可能感兴趣的文章
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
MFC模态对话框和非模态对话框
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB可视化客户端管理工具之NoSQLbooster4mongo
查看>>
Mongodb学习总结(1)——常用NoSql数据库比较
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
mongodb定时备份数据库
查看>>
mppt算法详解-ChatGPT4o作答
查看>>
mpvue的使用(一)必要的开发环境
查看>>
MQ 重复消费如何解决?
查看>>
mqtt broker服务端
查看>>