# CSPT27 Lecture 2 ## Num Good Pairs ``` class Solution: """ Understand nums = [1,2,3,1,1,3] output = 4 nums = [1,1,1,1] output = 6 nums = [1,2,3] output = 0 nums = [] output = 0 Plan Go through each possible pair, and count how many pairs are good pairs """ def numIdenticalPairs(self, nums: List[int]) -> int: numGoodPairs = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] == nums[j]: numGoodPairs += 1 return numGoodPairs ``` ## Richest Customer Wealth ``` class Solution: """ Understand accounts = [[1,2,3], [3,2,1]] output = 6 -------- accounts = [[1,2,3]] output = 6 -------- accounts = [[1,2,3], [3,2,1], [1,1,100]] output = 102 ----- accounts = [] output = 0 ----- Plan Keep track of maxWealthFound If the current customer's wealth is > maxWealthFound, update it Return maxWealthFound [[1,2,3], [3,2,1], [1,1,100]] maxWealthFound = 102 customerWealth = 102 """ def maximumWealth(self, accounts: List[List[int]]) -> int: maxWealthFound = 0 for customerAccounts in accounts: customerWealth = sum(customerAccounts) if customerWealth > maxWealthFound: maxWealthFound = customerWealth return maxWealthFound ``` ## N-Repeated Element ``` class Solution: """ nums.length == 2 * n n == nums.length / 2 nums = [1,2,3,3] output = 3 Plan Brute-force Approach For every element in nums, see if it occurs n times [1,2,3,4.......] Better Approach Use a dictionary to keep track of how many times the element occurs Go through the dictionary at the end, and output the element that occurs n-times { 1: 1, 2: 1, 3: 2, } [1,2,3,4.......] [1,2,3,3] counts = { 1: 1, 2: 1, 3: 2 } n = 2 """ def repeatedNTimes(self, nums: List[int]) -> int: counts = {} for num in nums: if num in counts: counts[num] += 1 else: counts[num] = 1 n = len(nums) / 2 for key, value in counts.items(): if value == n: return key ```