MediumNo. 1393
Capital Gain/Loss — LeetCode 1393 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
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
+---------------+---------+
| 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.