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

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

你可能感兴趣的文章
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>
MySQL5.6忘记root密码(win平台)
查看>>
MySQL5.6的Linux安装shell脚本之二进制安装(一)
查看>>
MySQL5.6的zip包安装教程
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>