Generate the Invoice — LeetCode 2362 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #2362
- Reading time
- 5 min
- Source
- leetcode.com
Table schema
SQL
Table: Products +-------------+------+ | Column Name | Type | +-------------+------+ | product_id | int | | price | int | +-------------+------+ product_id contains unique values. Each row in this table shows the ID of a product and the price of one unit.Example
SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id | int |
| price | int |
+-------------+------+
product_id contains unique values.
Each row in this table shows the ID of a product and the price of one unit.Python solution
Python
import duckdb
import pandas as pd
def solution(products: pd.DataFrame, purchases: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Products", products)
con.register("Purchases", purchases)
return con.execute("""WITH
P AS (
SELECT *
FROM
Purchases
JOIN Products USING (product_id)
),
T AS (
SELECT invoice_id, SUM(price * quantity) AS amount
FROM P
GROUP BY invoice_id
ORDER BY 2 DESC, 1
LIMIT 1
)
SELECT product_id, quantity, (quantity * price) AS price
FROM
P
JOIN T USING (invoice_id);""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2362. Generate the Invoice?
- LeetCode 2362. Generate the Invoice is rated Hard on LeetCode.
- What topics does LeetCode 2362. Generate the Invoice cover?
- LeetCode 2362. Generate the Invoice is tagged Database on LeetCode.
- Is LeetCode 2362. Generate the Invoice a premium problem?
- Yes. LeetCode 2362. Generate the Invoice is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.