
Sponsored
Sponsored
1import java.util.*;
2
3public List<Map<String, Object>> calculateCapitalGainLoss(List<Map<String, Object>> stocks) {
4 Map<String, List<Integer>> buyPrices = new HashMap<>();
5 Map<String, Integer> netGains = new HashMap<>();
6
7 for (Map<String, Object> stock : stocks) {
8 String name = (String)stock.get("stock_name");
9 String operation = (String)stock.get("operation");
10 int price = (int)stock.get("price");
11
12 if (operation.equals("Buy")) {
13 buyPrices.putIfAbsent(name, new LinkedList<>());
14 buyPrices.get(name).add(price);
15 } else if (operation.equals("Sell")) {
16 int buyPrice = buyPrices.get(name).remove(0);
17 int gainLoss = price - buyPrice;
18 netGains.put(name, netGains.getOrDefault(name, 0) + gainLoss);
19 }
20 }
21
22 List<Map<String, Object>> result = new ArrayList<>();
23 for (String name : netGains.keySet()) {
24 Map<String, Object> entry = new HashMap<>();
25 entry.put("stock_name", name);
26 entry.put("capital_gain_loss", netGains.get(name));
27 result.add(entry);
28 }
29 return result;
30}1function calculateCapitalGainLoss(stocks