前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[随缘一题]实现交易(fifo)

[随缘一题]实现交易(fifo)

作者头像
呼延十
发布2019-06-26 16:50:28
6850
发布2019-06-26 16:50:28
举报
文章被收录于专栏:呼延

来源:

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

代码语言:javascript
复制
buy 100 share(s) at $20 each
buy 20 share(s) at $24 each
buy 200 share(s) at $36 each
sell 150 share(s) at $30 each

得出计算结果 940.

优先卖掉持有时间最长的.

解题思路

直接使用Arraylist保存,卖出时从第一个开始即可.

当然也可以用队列做.

实现代码

代码语言:javascript
复制
/**
 * calculation the result
 * @param transactions
 * @return
 */
private Integer calculation(List<String> transactions) {
  int result = 0;

  //make the input to sell-100-20 format
  List<String> 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

更多学习笔记见个人博客——>呼延十

var gitment = new Gitment({ id: '[随缘一题]实现交易(fifo)', // 可选。默认为 location.href owner: 'hublanker', repo: 'blog', oauth: { client_id: '2297651c181f632a31db', client_secret: 'a62f60d8da404586acc965a2ba6a6da9f053703b', }, }) gitment.render('container')



本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 来源:
  • 解题思路
  • 实现代码
    • ChangeLog
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档