You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
numberOfBoxesi is the number of boxes of type i.
numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.
Return the maximum total number of units that can be put on the truck.
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda unit:unit[1], reverse=True)
ans = 0
for i in range(len(boxTypes)):
if boxTypes[i][0] > truckSize:
ans += truckSize * boxTypes[i][1]
break
else:
ans += boxTypes[i][0] * boxTypes[i][1]
truckSize -= boxTypes[i][0]
return ans
units 값들을 기준으로 오름차순 정렬한 후
박스 개수 * unit 개수
를 ans
에 저장
박스 개수가 truckSize
를 넘으면 truckSize * unit 개수
를 ans
에 저장
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
h = head
n = 0
while head:
n += 1
head = head.next
head = h
i = 0
l = head
r = head
while head:
i += 1
if i == k:
l = head
if i == n - k + 1:
r = head
head = head.next
l.val, r.val = r.val, l.val
return h
우선 총 몇개의 노드가 있는지 n
구하기
앞에서 k
번째 값과 뒤에서 k
번째 값을 찾아서
l
, r
에 저장한 후, 서로의 val 값 교환