# A. Find Closest Number to Zero (opens new window)
Iterate over all numbers, find the one with the smallest absolute value.
DETAILS
class Solution {
public int findClosestNumber(int[] nums) {
int ans = -1000000, dist = 1000000;
for (int num : nums) {
if (Math.abs(num) < dist) {
ans = num;
dist = Math.abs(num);
} else if (Math.abs(num) == dist) {
ans = Math.max(num, ans);
}
}
return ans;
}
}
# B. Number of Ways to Buy Pens and Pencils (opens new window)
Brute Force
DETAILS
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
ans = 0
while T >= 0:
ans += (T // c2) + 1
T -= c1
return ans2240. Number of Ways to Buy Pens and Pencils
# C. Design an ATM Machine (opens new window)
DETAILS
class ATM:
def __init__(self):
self.cnt = [0] * 5
self.d1 = {0:20, 1:50, 2:100, 3:200, 4:500}
def deposit(self, A: List[int]) -> None:
for i, a in enumerate(A):
self.cnt[i] += a
def withdraw(self, amount: int) -> List[int]:
i, ans = 4, [0] * 5
while i >= 0:
c = min(self.cnt[i], amount // self.d1[i])
amount -= c * self.d1[i]
ans[i] = c
i -= 1
if amount == 0:
for i, a in enumerate(ans):
self.cnt[i] -= a
return ans
else:
return [-1]
# D. Maximum Score of a Node Sequence (opens new window)
Since the chain's length is limited to 4, meaning there will ONLY be 3 edges in any valid chain. Thus we just focus on the middle edge consists of node a, b
, then we can just find the longest edge that from a
and b
, For example: c-a-b-d
, where c, d
are the nodes that have the longest edge from a, b
. Notice that some edge cases happen that a, b
be such furthest neighbor of each other, thus we will save the longest 3 neighbors instead.
DETAILS
class Solution:
def maximumScore(self, A: List[int], E: List[List[int]]) -> int:
n = len(A)
top3 = collections.defaultdict(list)
def func(a, b, e):
bisect.insort_left(top3[a], [e, b])
if len(top3[a]) > 3:
top3[a].pop(0)
for a, b in E:
func(a, b, A[b])
func(b, a, A[a])
ans = -1
for a, b in E:
if len(top3[a]) < 2 or len(top3[b]) < 2:
continue
for c in top3[a]:
for d in top3[b]:
if c[1] not in [a, b] and d[1] not in [a, b] and c[1] != d[1]:
ans = max(ans, A[a] + A[b] + c[0] + d[0])
return ans