Capital Gain/Loss — LeetCode 1393 Python Solution
MediumDatabase
- Problem
- #1393
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
Table: Stocks +---------------+---------+ | Column Name | Type | +---------------+---------+ | stock_name | varchar | | operation | enum | | operation_day | int | | price | int | +---------------+---------+ (stock_name, operation_day) is the primary key (combination of columns with unique values) for this table. The operation column is an ENUM (category) of type ('Sell', 'Buy') Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.Example
SQL
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| stock_name | varchar |
| operation | enum |
| operation_day | int |
| price | int |
+---------------+---------+
(stock_name, operation_day) is the primary key (combination of columns with unique values) for this table.
The operation column is an ENUM (category) of type ('Sell', 'Buy')
Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.
It is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day. It is also guaranteed that each 'Buy' operation for a stock has a corresponding 'Sell' operation in an upcoming day.Python solution
Python
import duckdb
import pandas as pd
def solution(stocks: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Stocks", stocks)
return con.execute("""SELECT
stock_name,
SUM(IF(operation = 'Buy', -price, price)) AS capital_gain_loss
FROM Stocks
GROUP BY 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1393. Capital Gain/Loss?
- LeetCode 1393. Capital Gain/Loss is rated Medium on LeetCode.
- What topics does LeetCode 1393. Capital Gain/Loss cover?
- LeetCode 1393. Capital Gain/Loss is tagged Database on LeetCode.