
Sponsored
Sponsored
1def calculate_capital_gain_loss(stocks):
2 gains = {}
3
4 for stock in stocks:
5 name = stock['stock_name']
6 operation = stock['operation']
7 price = stock['price']
8
9 if operation == 'Buy':
10 if name not in gains:
11 gains[name] = {'prices': [], 'net': 0}
12 gains[name]['prices'].append(price)
13 elif operation == 'Sell':
14 buy_price = gains[name]['prices'].pop(0)
15 gain_loss = price - buy_price
16 gains[name]['net'] += gain_loss
17
18 result = [{'stock_name': k, 'capital_gain_loss': v['net']} for k, v in gains.items()]
19 return result1#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;
}