[随缘一题]实现交易计算盈利

来源:

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

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

当然也可以用队列做.

实现代码

/**
 * 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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值