A dieter consumes calories[i] calories on the i-th day.
Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they look at T, the total calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]):
Note that the total points can be negative.
class Solution:
def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
points = 0
for i in range(len(calories)-k+1):
if sum(calories[i:i+k]) < lower:
points -= 1
if sum(calories[i:i+k]) > upper:
points += 1
return points
문제대로 했지만.. 내가 봐도... time limit ~
class Solution:
def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
sum_t = sum(calories[:k])
j, ans = 0, 0
if sum_t < lower: ans = -1
if sum_t > upper: ans = 1
for i in range(k, len(calories)):
sum_t -= calories[j]
sum_t += calories[i]
j += 1
if sum_t < lower: ans -= 1
if sum_t > upper: ans += 1
return ans
k
길이만큼의 합을 유지
맨 처음에 넣은 값을 빼주고 지금 보는 값을 더해주기
전에 풀었던 Sliding window 랑 유사한가봐요~
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
queue = [s]
subtree = s
# subtree 가 될만한 위치 찾기
while queue:
root = queue.pop(0)
if root:
queue.append(root.left)
queue.append(root.right)
if root.left and root.left.val == t.val:
subtree = root.left
if self.matchSubtree(subtree, t):
return True
if root.right and root.right.val == t.val:
subtree = root.right
if self.matchSubtree(subtree, t):
return True
if self.matchSubtree(subtree, t):
return True
return False
def matchSubtree(self, subtree, t):
# subtree 가 맞는지 확인
subq = [subtree]
tq = [t]
while subq:
subr = subq.pop(0)
tr = tq.pop(0)
if subr and tr:
if subr.val != tr.val:
return False
subq.append(subr.left)
subq.append(subr.right)
tq.append(tr.left)
tq.append(tr.right)
# 둘 중 하나라도 없으면 다른거니까 False
if subr and not tr or not subr and tr:
return False
return True