
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}1#include <iostream>
2#include <vector>
3#include <string>
#include <unordered_map>
#include <deque>
#include <algorithm>
struct Stock {
std::string stock_name;
std::string operation;
int operation_day;
int price;
};
bool compare(Stock a, Stock b) {
return a.operation_day < b.operation_day;
}
std::vector<std::pair<std::string, int>> calculateCapitalGainLoss(std::vector<Stock> stocks) {
std::unordered_map<std::string, std::deque<int>> buyPrices;
std::unordered_map<std::string, int> netGains;
std::sort(stocks.begin(), stocks.end(), compare);
for (auto& stock : stocks) {
if (stock.operation == "Buy") {
buyPrices[stock.stock_name].push_back(stock.price);
} else if (stock.operation == "Sell") {
int buyPrice = buyPrices[stock.stock_name].front();
buyPrices[stock.stock_name].pop_front();
int gainLoss = stock.price - buyPrice;
netGains[stock.stock_name] += gainLoss;
}
}
std::vector<std::pair<std::string, int>> result;
for (const auto& pair : netGains) {
result.push_back(pair);
}
return result;
}