來源:
根據先進先出原則實作交易.
例如:
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 完成
以上皆為個人所思所得,如有錯誤歡迎評論區指正。
歡迎轉載,煩請署名并保留原文連結。
聯系郵箱:[email protected]
更多學習筆記見個人部落格------>
呼延十