#1393

Capital Gain/Loss

Medium
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the data, leveraging a stack to keep track of buy prices. This allows us to efficiently calculate gains/losses without the need for nested loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dictionary to store total gain/loss for each stock.
  2. 2Step 2: Use a stack to keep track of buy prices for each stock.
  3. 3Step 3: For each transaction, if it's a 'Buy', push the price onto the stack; if it's a 'Sell', pop the last buy price and calculate the gain/loss.
solution.py14 lines
1def calculate_capital_gain(stocks):
2    gain_loss = {}
3    buy_prices = {}
4    for stock in stocks:
5        name, operation, day, price = stock
6        if operation == 'Buy':
7            if name not in buy_prices:
8                buy_prices[name] = []
9            buy_prices[name].append(price)
10        elif operation == 'Sell':
11            if name not in gain_loss:
12                gain_loss[name] = 0
13            gain_loss[name] += price - buy_prices[name].pop()  # pop last buy price
14    return gain_loss

Complexity note: The time complexity is O(n) because we only iterate through the list of transactions once. The space complexity is O(n) due to the storage of buy prices in a stack for each stock.

  • 1Each 'Sell' operation must correspond to a previous 'Buy' operation.
  • 2Using a stack allows for efficient tracking of prices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.