Investments in 2016 LeetCode Solution

Last updated on October 5th, 2024 at 04:31 pm

This Leetcode problem Investments in 2016 LeetCode Solution is done in SQL.

List of all LeetCode Solution

Companies

Twitter

Level of Question

Medium

Investments in 2016 LeetCode Solution

Investments in 2016 LeetCode Solution

Problem Statement

Column NameType
pidint
tiv_2015float
tiv_2016float
latfloat
lonfloat
Table: Insurance

pid is the primary key (column with unique values) for this table. Each row of this table contains information about one policy where:
pid is the policyholder’s policy ID.
tiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016.
lat is the latitude of the policy holder’s city. It’s guaranteed that lat is not NULL. lon is the longitude of the policy holder’s city. It’s guaranteed that lon is not NULL.

Write a solution to report the sum of all total investment values in 2016 tiv_2016, for all policyholders who: have the same tiv_2015 value as one or more other policyholders, and are not located in the same city as any other policyholder (i.e., the (lat, lon) attribute pairs must be unique).

Round tiv_2016 to two decimal places. The result format is in the following example.

Example 1:
Input:

pid tiv_2015 tiv_2016 lat lon
11051010
220202020
310302020
410404040
Insurance table:

Output:

tiv_2016
45.00

Explanation:
The first record in the table, like the last record, meets both of the two criteria. The tiv_2015 value 10 is the same as the third and fourth records, and its location is unique.
The second record does not meet any of the two criteria. Its tiv_2015 is not like any other policyholders and its location is the same as the third record, which makes the third record fail, too.
So, the result is the sum of tiv_2016 of the first and last record, which is 45.

1. Investments in 2016 LeetCode Solution MySQL

SELECT 
  ROUND(
    SUM(tiv_2016), 
    2
  ) AS tiv_2016 
FROM 
  Insurance 
WHERE 
  tiv_2015 IN (
    SELECT 
      tiv_2015 
    FROM 
      Insurance 
    GROUP BY 
      tiv_2015 
    HAVING 
      COUNT(*) > 1
  ) 
  AND (lat, lon) IN (
    SELECT 
      lat, 
      lon 
    FROM 
      Insurance 
    GROUP BY 
      lat, 
      lon 
    HAVING 
      COUNT(*) = 1
  )

2. Investments in 2016 LeetCode Solution Pandas

import pandas as pd
def find_investments(insurance: pd.DataFrame) -> pd.DataFrame:
  uniq_lat_lon = insurance.drop_duplicates(subset = ['lat','lon'], keep = False).pid
  not_uniq_tiv_2015 = insurance.loc[insurance.duplicated(subset = 'tiv_2015', keep=False)].pid
  df = insurance.loc[insurance.pid.isin(uniq_lat_lon) & insurance.pid.isin(not_uniq_tiv_2015)]
  return df[['tiv_2016']].sum().to_frame('tiv_2016').round(2)
Scroll to Top