Investments in 2016 — LeetCode 585 Python Solution
- Problem
- #585
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Report the total value invested in 2016 by the policyholders who share their 2015 investment value with at least one other policyholder and whose city is shared with nobody, rounded to two decimals. Two policyholders sit in the same city when their latitude and longitude are identical. The Insurance table has one row per policy: pid (int, the primary key), tiv_2015 (float, the total investment value in 2015), tiv_2016 (float, the total investment value in 2016), and lat and lon (float, the latitude and longitude of the policyholder's city, never null).
Example
Insurance table: | pid | tiv_2015 | tiv_2016 | lat | lon | | --- | -------- | -------- | ---- | ---- | | 1 | 45.00 | 120.25 | 12.0 | 8.0 | | 2 | 45.00 | 90.00 | 31.0 | 44.0 | | 3 | 45.00 | 75.00 | 31.0 | 44.0 | | 4 | 60.00 | 200.30 | 55.0 | 12.0 | | 5 | 60.00 | 150.00 | 70.0 | 25.0 | Result: | tiv_2016 | | -------- | | 470.55 | Policies 1, 4 and 5 each share their tiv_2015 with someone else and each sit at a location nobody else shares, so their 2016 values add up to 470.55; policies 2 and 3 share the location (31.0, 44.0) and drop out.
Python solution
import pandas as pd
def investments_2016(insurance: pd.DataFrame) -> pd.DataFrame:
tiv_count = insurance.groupby('tiv_2015')['pid'].transform('count')
loc_count = insurance.groupby(['lat', 'lon'])['pid'].transform('count')
filt = (tiv_count > 1) & (loc_count == 1)
total = insurance.loc[filt, 'tiv_2016'].sum()
return pd.DataFrame({'tiv_2016': [round(float(total), 2)]})Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 585. Investments in 2016?
- LeetCode 585. Investments in 2016 is rated Medium on LeetCode.
- What topics does LeetCode 585. Investments in 2016 cover?
- LeetCode 585. Investments in 2016 is tagged Database on LeetCode.