/** * calculation the result * @param transactions * @return */ private Integer calculation(List<String> transactions) { intresult=0;
//make the input to sell-100-20 format List<String> t = newArrayList<>(); for (String transaction : transactions) { if ("".equals(transaction)) { continue; } String[] ss = transaction.split(" "); t.add(ss[0] + "-" + ss[1] + "-" + ss[4].replace("$", "")); }
for (inti=0; i < t.size(); i++) { //cal while sell if (t.get(i).startsWith("sell")) { //get the num and the sell price intnum= Integer.valueOf(t.get(i).split("-")[1]); intsellPrice= Integer.valueOf(t.get(i).split("-")[2]); //cal the buy before sell for (intj=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]); } } } }