Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: barrier = 2 * target heap = [[0,0,1]] seen = {} while heap: step, position, speed = heappop(heap) if position == target: return step - 1 if (position,speed) in seen and seen[position,speed] <= step: continue seen[position,speed] = step k = 0 while True: new_pos = position + speed * (2 ** k - 1) if -barrier <= new_pos <= barrier: heappush(heap, [step + k + 1, new_pos, -speed]) else: break k += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: barrier = 2 * target heap = [[0,0,1]] seen = {} while heap: step, position, speed = heappop(heap) if position == target: return step - 1 if (position,speed) in seen and seen[position,speed] <= step: continue seen[position,speed] = step k = 0 while True: new_pos = position + speed * (2 ** k - 1) if -barrier <= new_pos <= barrier: heappush(heap, [step + k + 1, new_pos, -speed]) else: break k += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: max_step = int(log(target,2)) + 2 barrier = 2 * target + 2 heap = [[i + 1, 0 + (2 ** i - 1), -1] for i in range(max_step+1)] seen = {} while heap: step, position, speed = heappop(heap) if position == target: return step - 1 if (position,speed) in seen and seen[position,speed] <= step: continue seen[position,speed] = step k = 0 while True: new_pos = position + speed * (2 ** k - 1) if -barrier <= new_pos <= barrier: heappush(heap, [step + k + 1, new_pos, -speed]) else: break k += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: barrier = 2 * target heap = [[0,0,1]] seen = set() while heap: step, position, speed = heappop(heap) if position == target: return step - 1 if (position,speed) in seen: continue seen.add((position,speed)) k = 0 while True: new_pos = position + speed * (2 ** k - 1) if -barrier <= new_pos <= barrier: heappush(heap, [step + k + 1, new_pos, -speed]) else: break k += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0, 1, 4] + [float('inf')] * target for t in range(3, target + 1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue for j in range(k - 1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0,1,4] + [float('inf')] * target for t in range(3, target+1): k = t.bit_length() if t == 2**k-1: dp[t] = k continue for j in range(k-1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) # dp[t] = min(dp[t], dp[t - 2**(k - 1) + 1] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0, 1, 4] + [float('inf')] * target for i in range(3, target+1): k = i.bit_length() if i == 2**k-1: dp[i] = k continue for j in range(k-1): dp[i] = min(dp[i], dp[i-2**(k-1) + 2**j] + k-1+j+2) if 2**k-1-i < i: dp[i] = min(dp[i], dp[2**k-1-i]+k+1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution(object): def racecar(self, target): dp = [0, 1, 4] + [float('inf')] * target for t in range(3, target + 1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue for j in range(k - 1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # from answers: # Dojkstra's ''' K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0] ''' # Dynamic programming dp = [0, 1, 4] + [float('inf')] * target for t in range(3, target + 1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue for j in range(k - 1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: if target == 0: return 0 f = [None] * (target + 1) f[0] = 0 for i in range(1, target + 1): f[i] = float('inf') k = i.bit_length() if i == 2 ** k - 1: f[i] = k continue # underspeed for j in range(k - 1): f[i] = min(f[i], f[i - 2 ** (k - 1) + 2 ** j] + k - 1 + j + 2) # overspeed if 2 ** k - 1 - i < i: f[i] = min(f[i], f[2 ** k - 1 - i] + k + 1) return f[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: LIMIT = 2**(target.bit_length()) - 1 dp = [0, 1, 4] + [float('INF')]*(LIMIT-2) for t in range(3, target+1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue # not cross t, but first reverse to position t - 2**(k-1) + 2**j, then reverse and accelerate to t for j in range(k): dp[t] = min(dp[t], dp[t - 2**(k-1) + 2**j] + k + j + 1) # first cross t to 2**k - 1, then reverse to t dp[t] = min(dp[t], k + 1 + dp[2**k - 1 - t]) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def __init__(self): self._dp = {0:0} def racecar(self, target): # 车子初始位置0,速度1 # 遇到A,position += speed并且speed *= 2 # 遇到R,speed = -1如果当前speed是1;speed = 1如果 # 给定最终的位置target,问最短的sequence(由A和R组成)能够到达target if target == 0: return 0 if target == 1: return 1 if target == 2: return 4 # 如果一直踩油门的话(连续3个A) # 则会到达0 -> 1 -> 3 -> 7 # k=1 k=2 k=3 dp = [2 ** 31 - 1] * (target + 1) dp[0], dp[1], dp[2] = 0, 1, 4 for t in range(3, target + 1): k = t.bit_length() if t == 2 ** k - 1: # t = 7, 二进制111, k = 3 # 此时表明踩3脚油门就能到了 dp[t] = k continue # 情况1:走2 ** (k - 1)的距离 # 然后用一个R和m个A去往回走 # 这时候已经走了k - 1 + 1 + m + 1步(即A**(k - 1)RA**(m)R步) # 然后去dp里找剩余的步数t - 2 ** (k - 1) + 2 ** m for m in range(k - 1): # 注意:后面的k - 1 + m + 2是当前走了这么多步 dp[t] = min(dp[t], dp[t - 2 ** (k - 1) + 2 ** m] + k - 1 + m + 2) # 情况2:直接2 ** k步 #(已经走了最大的k + 1步, 就是在最后min函数括号里加的那一部分,加1是指一个R) # 然后再往回走 # 走了k + 1步距离就是2 ** k - 1,这个距离已经超越了t # 所以还要继续走2 ** k - 1 - t步才能走到t if 2 ** k - 1 - t > 0: dp[t] = min(dp[t], dp[2 ** k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target): # 车子初始位置0,速度1 # 遇到A,position += speed并且speed *= 2 # 遇到R,speed = -1如果当前speed是1;speed = 1如果 # 给定最终的位置target,问最短的sequence(由A和R组成)能够到达target if target == 0: return 0 if target == 1: return 1 if target == 2: return 4 # 如果一直踩油门的话(连续3个A) # 则会到达0 -> 1 -> 3 -> 7 # k=1 k=2 k=3 dp = [2 ** 31 - 1] * (target + 1) dp[0], dp[1], dp[2] = 0, 1, 4 for t in range(3, target + 1): k = t.bit_length() if t == 2 ** k - 1: # t = 7, 二进制111, k = 3 # 此时表明踩3脚油门就能到了 dp[t] = k continue # 此时必定 2 ** (k - 1) <= t <= 2 ** (k + 1) assert 2 ** (k - 1) <= t <= 2 ** (k + 1) # 情况1:走k - 1步,还没到t,回头再回头的策略 # 然后用一个R和m个A去往回走 # 这时候已经走了k - 1 + 1 + m + 1步(即A**(k - 1)RA**(m)R步) # 然后去dp里找剩余的步数t - 2 ** (k - 1) + 2 ** m for m in range(k - 1): # 注意:后面的k - 1 + m + 2是当前走了这么多步 dp[t] = min(dp[t], dp[t - 2 ** (k - 1) + 2 ** m] + k - 1 + m + 2) # 情况2:直接k步,假设能够超过t,就采取再回头的策略 #(已经走了k步, 就是在最后min函数括号里加的那一部分,加1是指一个R) # 然后再往回走 # 走了k步距离就是2 ** k - 1,这个距离已经超越了t # 所以还要继续走2 ** k - 1 - t步才能走到t if 2 ** k - 1 - t > 0: dp[t] = min(dp[t], dp[2 ** k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target): # 车子初始位置0,速度1 # 遇到A,position += speed并且speed *= 2 # 遇到R,speed = -1如果当前speed是1;speed = 1如果 # 给定最终的位置target,问最短的sequence(由A和R组成)能够到达target if target == 0: return 0 if target == 1: return 1 if target == 2: return 4 # 如果一直踩油门的话(连续3个A) # 则会到达0 -> 1 -> 3 -> 7 # k=1 k=2 k=3 # dp[t]的定义是到达t位置最少需要走多少步 dp = [2 ** 31 - 1] * (target + 1) dp[0], dp[1], dp[2] = 0, 1, 4 for t in range(3, target + 1): k = t.bit_length() if t == 2 ** k - 1: # t = 7, 二进制111, k = 3 # 此时表明踩3脚油门就能到了 dp[t] = k continue # 此时必定 2 ** (k - 1) <= t <= 2 ** (k + 1) assert 2 ** (k - 1) <= t <= 2 ** (k + 1) # 情况1:走k - 1步,还没到t,回头再回头的策略 # 然后用一个R和m个A去往回走 # 这时候已经走了k - 1 + 1 + m + 1步(即A**(k - 1)RA**(m)R步) # 然后去dp里找剩余的步数t - 2 ** (k - 1) + 2 ** m for m in range(k - 1): # 注意:后面的k - 1 + m + 2是当前走了这么多步 dp[t] = min(dp[t], dp[t - 2 ** (k - 1) + 2 ** m] + k - 1 + m + 2) # 情况2:直接k步,假设能够超过t,就采取再回头的策略 #(已经走了k步, 就是在最后min函数括号里加的那一部分,加1是指一个R) # 然后再往回走 # 走了k步距离就是2 ** k - 1,这个距离已经超越了t # 所以还要继续走2 ** k - 1 - t步才能走到t if 2 ** k - 1 - t > 0: dp[t] = min(dp[t], dp[2 ** k - 1 - t] + k + 1) return dp[target] # BFS解法,非最优,但是好想 # queue = deque([(0, 1)]) # # 状态是(location, speed) # visited = set([(0, 1)]) # res = 0 # while queue: # q_len = len(queue) # for _ in range(q_len): # curr_pos, curr_speed = queue.popleft() # if curr_pos == target: # return res # # case-1: 当前选择A # new_pos = curr_pos + curr_speed # new_speed = 2 * curr_speed # if (new_pos, new_speed) not in visited: # queue.append((new_pos, new_speed)) # visited.add((new_pos, new_speed)) # # case-2: 当前选择R # new_pos = curr_pos # new_speed = -1 if curr_speed > 0 else 1 # if (new_pos, new_speed) not in visited: # queue.append((new_pos, new_speed)) # visited.add((new_pos, new_speed)) # res += 1 # return res
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: queue = deque([(0, 1)]) # position, speed level = 0 while True: size = len(queue) for _ in range(size): position, speed = queue.popleft() if position == target: return level queue.append((position + speed, speed * 2)) if position + speed > target and speed > 0 or position + speed < target and speed < 0: queue.append((position, -1 if speed > 0 else 1)) level += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: f = [None] * (target + 1) f[0] = 0 for i in range(1, target + 1): f[i] = float('inf') k = i.bit_length() if i == 2**k - 1: f[i] = k continue # underspeed for j in range(k - 1): f[i] = min(f[i], f[i - 2**(k - 1) + 2**j] + k - 1 + j + 2) # overspeed if 2**k - 1 - i < i: f[i] = min(f[i], f[2**k - 1 - i] + k + 1) return f[target] # f = [None] * (target + 1) # f[0] = 0 # for i in range(1, target + 1): # f[i] = float('inf') # n = len(bin(i)[2:]) # if 2**n - 1 == i: # f[i] = n # continue # # overspeed # f[i] = f[2**n - 1 - i] + n + 1 # reverse once # # underspeed # for j in range(0, n): # gap = 1 << j - 1 # f[i] = min(f[i], f[i - 2**(n - 1) + gap] + n + j + 1) # reverse twice # return f[target] # int[] f = new int[target + 1]; # for (int i = 1; i <= target; i++){ # int bound = (Integer.highestOneBit(i) << 1) - 1; # int n = Integer.bitCount(bound); # if (i == bound){ # f[i] = n; # continue; # } # // overspeed # f[i] = f[bound - i] + n + 1; // Reverse once # // underspeed # bound >>= 1; # for (int j = 0; j < n; j++){ # int gap = (1 << j) - 1; # f[i] = Math.min(f[i], f[i - bound + gap] + n + j + 1); // Reverse twice # } # } # return f[target]; # } # }
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target): dp = [0, 1, 4] + [float('inf')] * target for t in range(3, target + 1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue for j in range(k - 1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target] # 比较难的一道题目,想了几天无果看了官方给的题解,还是很巧妙的。 # 用Ak表示k次连续的A,首先结尾一定不是R,开头的RAk可以放到最后。 # 那么最终指令应该形如Ak1RAk2R…RAkn。 # 容易得到奇数的ki与偶数的ki都是单调递减的,且各不相同。 # 并且到达或者超过目标位置之后继续执行A是没有意义的。 # 因此就有了DP的做法,如果下标位置是2k−1,那么可以直接Ak达到。 # 否则有两种情况,一是拐两次到达,正面一定有一次最大限度的2k−1,外加返回走j步(枚举j)。 # 二是直接走刚好超过2k−1,回走到终点。 # def racecar(self, target: int) -> int: # # 0 -> 1 -> 3 -> 7 - > 15 # # 1 -> 2 -> 4 -> 8 -> 16 # # 从 0 出发,每次可以 R 或 A两个方向,选择。 # # 可以记录每次到达的状态, # # BFS # d = deque([(0, 0, 1)]) # visited = collections.defaultdict(set) # visited[0].add(1) # ans = float('inf') # flag = 0 # while d: # flag += 1 # # print(\"flag=\", flag,\", d=\", d) # l = len(d) # while l: # l -= 1 # cur = d.popleft() # # print(\"cur=\", cur) # pos, cost, speed = cur # if pos == target: # ans = min(ans, cost) # # continue # return cost # # use R # cost += 1 # if 1: # newspeed = -1 if speed > 0 else 1 # if not ((pos in visited and newspeed in visited[pos]) or (pos <= 0)): # # print(\"past=\", cur,\", add=\", (pos, cost, -1)) # d.append(((pos, cost, newspeed))) # visited[pos].add(newspeed) # # 这里 if 里 break 不要瞎用,会跳出 while l 这个循环的。 # # use A # if 1: # if not (( speed in visited and (cost, speed * 2) in visited[pos]) or (pos + speed > target * 2) or (pos + speed <= 0)): # # print(\"past=\", cur,\", add=\", (pos + speed, cost, speed * 2)) # d.append((pos + speed, cost, speed * 2)) # visited[pos].add(speed * 2) # return # # BFS 搞了半天,终于结束了。注意要剪枝。 # # 1. 首先 visited 加入的是 pos 和 speed。 # # 2. 第二是 位置不能超过 target * 2 。因为 如果超过了 target * 2那么要倒车,倒车从头开始,也要 走 target。这是 不合算的。 # # 3. 速度不能超过 2*target。 (可以不要) # # 4. 不要 pos <0 的位置。 # # pos 0 1 3 2 3 # # speed 1 2 -1 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: queue = collections.deque() visited = set() queue.append((0, 1)) visited.add((0, 1)) steps = 0 while queue: size = len(queue) for i in range(size): pos, speed = queue.popleft() if pos == target: return steps # Option 1: do acceleration, if it is not counter productive. next_pos = pos + speed if 0 < next_pos < 2 * target: next_state = (next_pos, 2 * speed) if next_state not in visited: visited.add(next_state) queue.append(next_state) # Option 2: do reverse. next_speed = -1 if speed > 0 else 1 next_state = (pos, next_speed) if next_state not in visited: visited.add(next_state) queue.append(next_state) steps += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target): # 车子初始位置0,速度1 # 遇到A,position += speed并且speed *= 2 # 遇到R,speed = -1如果当前speed是1;speed = 1如果 # 给定最终的位置target,问最短的sequence(由A和R组成)能够到达target if target == 0: return 0 if target == 1: return 1 if target == 2: return 4 # 如果一直踩油门的话(连续3个A) # 则会到达0 -> 1 -> 3 -> 7 # k=1 k=2 k=3 dp = [2 ** 31 - 1] * (target + 1) dp[0], dp[1], dp[2] = 0, 1, 4 for t in range(3, target + 1): k = t.bit_length() if t == 2 ** k - 1: # t = 7, 二进制111, k = 3 # 此时表明踩3脚油门就能到了 dp[t] = k continue # 此时必定 2 ** (k - 1) <= t <= 2 ** (k + 1) assert 2 ** (k - 1) <= t <= 2 ** (k + 1) # 情况1:走2 ** (k - 1)的距离 # 然后用一个R和m个A去往回走 # 这时候已经走了k - 1 + 1 + m + 1步(即A**(k - 1)RA**(m)R步) # 然后去dp里找剩余的步数t - 2 ** (k - 1) + 2 ** m for m in range(k - 1): # 注意:后面的k - 1 + m + 2是当前走了这么多步 dp[t] = min(dp[t], dp[t - 2 ** (k - 1) + 2 ** m] + k - 1 + m + 2) # 情况2:直接2 ** k步 #(已经走了最大的k + 1步, 就是在最后min函数括号里加的那一部分,加1是指一个R) # 然后再往回走 # 走了k + 1步距离就是2 ** k - 1,这个距离已经超越了t # 所以还要继续走2 ** k - 1 - t步才能走到t if 2 ** k - 1 - t > 0: dp[t] = min(dp[t], dp[2 ** k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: a,d,m,s=[(0,1)],set([(0,1)]),2*target,0 while 1: b,s=[],s+1 for i,j in a: ii,jj,k=i+j,2*j,-1 if j>0 else 1 if ii==target: return s if (ii,jj) not in d and 0<ii<m: b.append((ii,jj)) d.add((ii,jj)) if (i,k) not in d: b.append((i,k)) d.add((i,k)) a=b
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def __init__(self): self._dp = {0:0} def racecar(self, target): # 车子初始位置0,速度1 # 遇到A,position += speed并且speed *= 2 # 遇到R,speed = -1如果当前speed是1;speed = 1如果 # 给定最终的位置target,问最短的sequence(由A和R组成)能够到达target # dp = [0, 1, 4] + [2 ** 31 - 1] * target if target == 0: return 0 if target == 1: return 1 if target == 2: return 4 dp = [2 ** 31 - 1] * (target + 1) dp[0], dp[1], dp[2] = 0, 1, 4 for t in range(3, target + 1): k = t.bit_length() if t == 2 ** k - 1: dp[t] = k continue # 情况1:走2 ** (k - 1)的距离 # 然后用一个R和m个A去往回走 # 这时候已经走了(k - 1) + 1 + (m - 1) + 1 + 2步(即A**(k - 1)RA**(m - 1)R # 然后去dp里找剩余的步数t - 2 ** (k - 1) + 2 ** m for m in range(k - 1): # 注意:后面的k - 1 + j + 2是当前走了这么多步 dp[t] = min(dp[t], dp[t - 2 ** (k - 1) + 2 ** m] + k - 1 + m + 2) # 情况2:直接2 ** k步(已经走了最大的k + 1步, 就是在最后min函数括号里加的那一部分,加1是指一个R),然后再往回走 # 走了k + 1步距离就是2 ** k - 1,这个距离已经超越了t # 所以还要继续走2 ** k - 1 - t步才能走到t if 2 ** k - 1 - t > 0: dp[t] = min(dp[t], dp[2 ** k - 1 - t] + k + 1) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: queue = deque([(0,1)]) # start with pos 0, speed 1 visited = set((0,1)) level = 0 while queue: num = len(queue) for _ in range(num): cur_pos, cur_speed = queue.popleft() if cur_pos == target: return level # accelerate instruction nex_acc = (cur_pos + cur_speed, cur_speed*2) if nex_acc not in visited and 0 < nex_acc[0] < target*2: queue.append(nex_acc) visited.add(nex_acc) nex_rev = (cur_pos, -1 if cur_speed > 0 else 1) if nex_rev not in visited and 0 < nex_rev[0] < target*2: queue.append(nex_rev) visited.add(nex_rev) level += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: q = deque([(0, 1)]) visited = set([(0, 1)]) step = 0 while q: l = len(q) step += 1 for _ in range(l): pos, speed = q.popleft() if pos == target: return step - 1 new_pos, new_speed = pos + speed, speed * 2 if (new_pos, new_speed) not in visited and 0 < new_pos <= target * 2: q.append((new_pos, new_speed)) visited.add((new_pos, new_speed)) new_pos, new_speed = pos, -1 if speed > 0 else 1 if (new_pos, new_speed) not in visited and 0 < new_pos <= target * 2: q.append((new_pos, new_speed)) visited.add((new_pos, new_speed)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: if target == 0: return 0 # BFS solution level = 0 q = deque([(0, 1)]) # tuple of (pos, speed) visited = {(0, 1),} while q: length = len(q) for _ in range(length): p, s = q.popleft() # use A new_p, new_s = p + s, 2*s if new_p == target: return level + 1 if 0 < new_p < 2* target and (new_p, new_s) not in visited: visited.add((new_p, new_s)) q.append((new_p, new_s)) # use R new_p, new_s = p, -s//abs(s) if 0 < new_p < 2* target and (new_p, new_s) not in visited: visited.add((new_p, new_s)) q.append((new_p, new_s)) level += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0, 1, 4] + [float('inf')] * target for t in range(3, target + 1): k = t.bit_length() if t == 2**k - 1: dp[t] = k continue for j in range(k - 1): dp[t] = min(dp[t], dp[t - 2**(k - 1) + 2**j] + k - 1 + j + 2) if 2**k - 1 - t < t: dp[t] = min(dp[t], dp[2**k - 1 - t] + k + 1) return dp[target] # f = [None] * (target + 1) # f[0] = 0 # for i in range(1, target + 1): # f[i] = float('inf') # n = len(bin(i)[2:]) # if 2**n - 1 == i: # f[i] = n # continue # # overspeed # f[i] = f[2**n - 1 - i] + n + 1 # reverse once # # underspeed # for j in range(0, n): # gap = 1 << j - 1 # f[i] = min(f[i], f[i - 2**(n - 1) + gap] + n + j + 1) # reverse twice # return f[target] # int[] f = new int[target + 1]; # for (int i = 1; i <= target; i++){ # int bound = (Integer.highestOneBit(i) << 1) - 1; # int n = Integer.bitCount(bound); # if (i == bound){ # f[i] = n; # continue; # } # // overspeed # f[i] = f[bound - i] + n + 1; // Reverse once # // underspeed # bound >>= 1; # for (int j = 0; j < n; j++){ # int gap = (1 << j) - 1; # f[i] = Math.min(f[i], f[i - bound + gap] + n + j + 1); // Reverse twice # } # } # return f[target]; # } # }
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: q = deque([(0, 1)]) visited = set([(0, 1)]) upper = target * 2 step = 0 while q: l = len(q) step += 1 for _ in range(l): pos, speed = q.popleft() if pos == target: return step - 1 new_pos, new_speed = pos + speed, speed * 2 if (new_pos, new_speed) not in visited and 0 < new_pos <= upper: q.append((new_pos, new_speed)) visited.add((new_pos, new_speed)) new_pos, new_speed = pos, -1 if speed > 0 else 1 if (new_pos, new_speed) not in visited and 0 < new_pos <= upper: q.append((new_pos, new_speed)) visited.add((new_pos, new_speed)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: queue = collections.deque([(1, 0)]) visited = set(queue) count = 0 while queue: for _ in range(len(queue)): speed, pos = queue.popleft() if pos < 0: continue if pos > 2*target: continue if target == pos: return count if (speed*2, pos+speed) not in visited: visited.add((speed*2, pos+speed)) queue.append((speed*2, pos+speed)) if speed > 0: if (-1, pos) not in visited: visited.add((-1, pos)) queue.append((-1, pos)) else: if (1, pos) not in visited: visited.add((1, pos)) queue.append((1, pos)) count += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: queue = collections.deque() visited = set() queue.append((0, 1, 0)) visited.add((0, 1)) while queue: pos, speed, steps = queue.popleft() if pos == target: return steps next_pos = pos + speed next_speed = speed * 2 if (next_pos, next_speed) not in visited and next_pos < 2 * target and next_pos > 0: queue.append((next_pos, next_speed, steps + 1)) visited.add((next_pos, next_speed)) next_pos = pos next_speed = -1 if speed > 0 else 1 if (next_pos, next_speed) not in visited and next_pos < 2 * target and next_pos > 0: queue.append((next_pos, next_speed, steps + 1)) visited.add((next_pos, next_speed)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import * class Solution: def racecar(self, t: int) -> int: q, s, lvl = deque([(0, 1)]), set([(0, 1)]), 0 while q: for _ in range(len(q)): pu, su = q.popleft() if pu == t: return lvl a, r = (pu + su, su * 2), (pu, -1 if su > 0 else 1) for e in (a, r): if e in s or e[0] < 0 or e[0] >= t * 2: continue q.append(e) s.add(e) lvl += 1 return 0
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # 0 -> 1 -> 3 -> 7 - > 15 # 1 -> 2 -> 4 -> 8 -> 16 # 从 0 出发,每次可以 R 或 A两个方向,选择。 # 可以记录每次到达的状态, # BFS d = deque([(0, 0, 1)]) visited = collections.defaultdict(set) visited[0].add(1) ans = float('inf') flag = 0 while d: flag += 1 # print(\"flag=\", flag,\", d=\", d) l = len(d) while l: l -= 1 cur = d.popleft() # print(\"cur=\", cur) pos, cost, speed = cur if pos == target: ans = min(ans, cost) # continue return cost # use R cost += 1 if 1: newspeed = -1 if speed > 0 else 1 if not ((pos in visited and newspeed in visited[pos]) or (pos <= 0)): # print(\"past=\", cur,\", add=\", (pos, cost, -1)) d.append(((pos, cost, newspeed))) visited[pos].add(newspeed) # 这里 if 里 break 不要瞎用,会跳出 while l 这个循环的。 # use A if 1: if not (( speed in visited and (cost, speed * 2) in visited[pos]) or (pos + speed > target * 2) or (pos + speed <= 0)): # print(\"past=\", cur,\", add=\", (pos + speed, cost, speed * 2)) d.append((pos + speed, cost, speed * 2)) visited[pos].add(speed * 2) return # BFS 搞了半天,终于结束了。注意要剪枝。 # 1. 首先 visited 加入的是 pos 和 speed。 # 2. 第二是 位置不能超过 target * 2 # 3. 速度不能超过 2*target。 (可以不要) # 4. 不要 pos <0 的位置。 # pos 0 1 3 2 3 # speed 1 2 -1 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: visited = set() q = deque([(0,1,0)]) while q: pos, sp, d = q.popleft() #print(pos, q) if pos==target: return d if pos<-1 or pos>1.5*target or sp>1.5*target or (pos, sp) in visited: continue visited.add((pos, sp)) q.append((pos+sp, sp*2, d+1)) q.append((pos, -1*(sp//abs(sp)), d+1))
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: queue = deque([(0, 1)]) visited = set([(0, 1)]) step = 0 while queue: level_size = len(queue) # print(queue) for _ in range(level_size): posi, spd = queue.popleft() if posi == target: return step if ((posi+spd, 2*spd) not in visited) and posi+spd>0 and posi+spd < target<<1: queue.append((posi+spd, 2*spd)) visited.add((posi+spd, 2*spd)) sign = 1 if spd > 0 else -1 if ((posi, -sign) not in visited) and posi >0 and posi < target<<1: queue.append((posi, -sign)) visited.add((posi, -sign)) step += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: visited = set() q = deque([(0,1,0)]) while q: pos, sp, d = q.popleft() #print(pos, q) if pos==target: return d if (pos, sp) in visited: continue visited.add((pos, sp)) if abs(sp)>target or pos<0: # in these cases, must turn. q.append((pos, -1*(sp//abs(sp)), d+1)) else: # can keep goint or turn. q.append((pos+sp, sp*2, d+1)) q.append((pos, -1*(sp//abs(sp)), d+1))
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # 0 -> 1 -> 3 -> 7 - > 15 # 1 -> 2 -> 4 -> 8 -> 16 # 从 0 出发,每次可以 R 或 A两个方向,选择。 # 可以记录每次到达的状态, # BFS d = deque([(0, 0, 1)]) visited = collections.defaultdict(set) visited[0].add(1) ans = float('inf') flag = 0 while d: flag += 1 # print(\"flag=\", flag,\", d=\", d) l = len(d) while l: l -= 1 cur = d.popleft() # print(\"cur=\", cur) pos, cost, speed = cur if pos == target: ans = min(ans, cost) # continue return cost # use R cost += 1 if 1: newspeed = -1 if speed > 0 else 1 if not ((pos in visited and newspeed in visited[pos]) or (pos <= 0)): # print(\"past=\", cur,\", add=\", (pos, cost, -1)) d.append(((pos, cost, newspeed))) visited[pos].add(newspeed) # 这里 if 里 break 不要瞎用,会跳出 while l 这个循环的。 # use A if 1: if not (( speed in visited and (cost, speed * 2) in visited[pos]) or (pos + speed > target * 2) or (pos + speed <= 0) or (speed > 2*target)): # print(\"past=\", cur,\", add=\", (pos + speed, cost, speed * 2)) d.append((pos + speed, cost, speed * 2)) visited[pos].add(speed * 2) return # pos 0 1 3 2 3 # speed 1 2 -1 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # 0 -> 1 -> 3 -> 7 - > 15 # 1 -> 2 -> 4 -> 8 -> 16 # 从 0 出发,每次可以 R 或 A两个方向,选择。 # 可以记录每次到达的状态, # BFS d = deque([(0, 0, 1)]) visited = collections.defaultdict(set) visited[0].add(1) ans = float('inf') flag = 0 while d: flag += 1 # print(\"flag=\", flag,\", d=\", d) l = len(d) while l: l -= 1 cur = d.popleft() # print(\"cur=\", cur) pos, cost, speed = cur if pos == target: ans = min(ans, cost) # continue return cost # use R cost += 1 if 1: newspeed = -1 if speed > 0 else 1 if not ((pos in visited and newspeed in visited[pos]) or (pos <= 0)): # print(\"past=\", cur,\", add=\", (pos, cost, -1)) d.append(((pos, cost, newspeed))) visited[pos].add(newspeed) # 这里 if 里 break 不要瞎用,会跳出 while l 这个循环的。 # use A if 1: if not (( speed in visited and (cost, speed * 2) in visited[pos]) or (pos + speed > target * 2) or (pos + speed <= 0)): # print(\"past=\", cur,\", add=\", (pos + speed, cost, speed * 2)) d.append((pos + speed, cost, speed * 2)) visited[pos].add(speed * 2) return # BFS 搞了半天,终于结束了。注意要剪枝。 # 1. 首先 visited 加入的是 pos 和 speed。 # 2. 第二是 位置不能超过 target * 2 # 3. 速度不能超过 2*target。 # 4. 不要 pos <0 的位置。 # pos 0 1 3 2 3 # speed 1 2 -1 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dq = collections.deque([(0, 1)]) seen = set([(0,1)]) depth = 0 while True: k = len(dq) while k: (pos, velo) = dq.popleft() if pos == target: return depth cand = [(pos, -1 if velo>0 else 1)] if abs(target- (pos+velo)) < target: cand.append((pos+velo, velo*2)) for (p, v) in cand: if (p, v) not in seen: seen.add((p,v)) dq.append((p,v)) k-=1 depth+=1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: queue = deque([(0,1)]) visited=set() visited.add((0,1)) step = 0 while queue: for _ in range(len(queue)): pos, speed = queue.popleft() if pos+speed==target: return step+1 if abs(speed*2)<2*target and abs(pos+speed)<2*target: queue.append((pos+speed,speed*2)) if speed>0: speed2=-1 else: speed2=1 if (pos,speed2) not in visited: queue.append((pos,speed2)) visited.add((pos,speed2)) step+=1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: visited = set() q = deque([(0,1,0)]) while q: pos, sp, d = q.popleft() #print(pos, q) if pos==target: return d if pos<-1 or pos>2*target or sp>2*target or (pos, sp) in visited: continue visited.add((pos, sp)) q.append((pos+sp, sp*2, d+1)) q.append((pos, -1*(sp//abs(sp)), d+1))
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: queue = deque([(0,1)]) visited=set() visited.add((0,1)) step = 0 while queue: for _ in range(len(queue)): pos, speed = queue.popleft() if pos+speed==target: return step+1 if abs(speed*2)-1<2*target and abs(pos+speed)-2<2*target: queue.append((pos+speed,speed*2)) if speed>0: speed2=-1 else: speed2=1 if (pos,speed2) not in visited: queue.append((pos,speed2)) visited.add((pos,speed2)) step+=1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: q = collections.deque([(0, 1, 0)]) visited = set() visited.add((0,1)) while q: size = len(q) for _ in range(size): pos, speed, steps = q.popleft() if pos == target: return steps cand = [] if abs(target - (pos + speed)) < target: cand.append((pos + speed, 2 * speed)) cand.append([pos, 1 if speed < 0 else -1]) for pos, speed in cand: if (pos, speed) not in visited: q.append((pos, speed, steps + 1)) visited.add((pos, speed)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: def dfs(t): if t in dp: return dp[t] n = t.bit_length() if 2**n - 1 == t: dp[t] = n else: dp[t] = dfs(2**n - 1 - t) + n + 1 for m in range(n - 1): dp[t] = min(dp[t], dfs(t - 2**(n - 1) + 2**m) + n + m + 1) return dp[t] dp = {0:0} return dfs(target)
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: visited = set() q = deque([(0,1,0)]) while q: pos, sp, d = q.popleft() #print(pos, q) if pos==target: return d if (pos, sp) in visited: continue visited.add((pos, sp)) if abs(sp)>target or pos<-1: # in these cases, must turn. q.append((pos, -1*(sp//abs(sp)), d+1)) else: # can keep goint or turn. q.append((pos+sp, sp*2, d+1)) q.append((pos, -1*(sp//abs(sp)), d+1))
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: states = set([(0, 1)]) que = collections.deque([[0, 1]]) cost = 0 while que: for _ in range(len(que)): pos, speed = que.popleft() if pos == target: return cost #if abs(pos) >= 2 * target: # continue if pos < 0 or pos >= 2 * target: continue for npos, nspeed in [[pos, 1 if speed < 0 else -1], [pos + speed, speed * 2]]: if (npos, nspeed) not in states: states.add((npos, nspeed)) que.append([npos, nspeed]) cost += 1 return -1 dp = {0: 0} def racecar_DP(self, t): if t in self.dp: return self.dp[t] n = t.bit_length() if (1 << n) - 1 == t: self.dp[t] = n else: self.dp[t] = self.racecar(2**n - 1 - t) + n + 1 for m in range(n - 1): self.dp[t] = min(self.dp[t], self.racecar(t - 2**(n - 1) + 2**m) + n + m + 1) return self.dp[t]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: targetLen = len(bin(target)) - 2 barrier = (1 << targetLen) # print(tar6021getLen, barrier) stack = [(0, target)] dp = {target:0} while stack: # print(stack) step0, dist = heapq.heappop(stack) for i in range(targetLen+1): move = (1<<i)-1 step1 = step0 + i if move != dist: step1 += 1 newDist = -(dist - move) if abs(newDist) <= barrier and (newDist not in dp or dp[newDist] > step1): heapq.heappush(stack, (step1, newDist)) dp[newDist] = step1 return dp[0] # stack = [(0, 0, 1)] # visited = {(0,1):0} # while stack: # stepNow, loc, speed = heapq.heappop(stack) # if visited[(loc, speed)] < stepNow: # continue # loc1 = loc+speed # speed1 = speed*2 # if loc1 == target: # return stepNow + 1 # if (loc1, speed1) not in visited or visited[(loc1, speed1)] > stepNow+1: # visited[(loc1, speed1)] = stepNow + 1 # heapq.heappush(stack, (stepNow +1, loc1, speed1)) # loc1 = loc # speed1 = -1 if speed > 0 else 1 # if (loc1, speed1) not in visited or visited[(loc1, speed1)] > stepNow+1: # visited[(loc1, speed1)] = stepNow + 1 # heapq.heappush(stack, (stepNow +1, loc1, speed1))
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0] * (target+1) for i in range(1, target+1): dp[i] = float('inf') j = 1 m = 1 while j < i: p = 0 q = 0 while q < j: dp[i] = min(dp[i], dp[i-(j-q)] + m + 1 + p + 1) p += 1 q = (1<<p) - 1 m += 1 j = (1<<m) - 1 dp[i] = min(dp[i], m if j == i else m + 1 + dp[j-i]) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: dp = [0] * (target+1) for i in range(1, target+1): dp[i] = float('inf') j = 1 m = 1 while j < i: p = 0 q = 0 while q < j: dp[i] = min(dp[i], dp[i-(j-q)] + m + 1 + p + 1) p += 1 q = (1<<p) - 1 m += 1 #print('j', m>>1-1, m, (m<<1) - 1) j = (1<<m) - 1 #print(i, j) # if i == 6: # print(m, dp[j-1]) dp[i] = min(dp[i], m if j == i else m + 1 + dp[j-i]) return dp[target]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, tgt: int) -> int: ''' shortest path -> bfs starting from [0, 1], how to reach tgt = 5? [0, 1] -> [1, 2], [0, -1] [1, 2] -> [3, 4], [1, -1] [0, -1] ->[-1, -2], [0, 1] ... visited [3, 4] -> [3, -1], [7, 8] [1,-1] -> [0, -2], [1, 1] [-1,-2]-> [-3,-4] ... too far, [-1,1] [3, -1] -> [2, -2], [3, 1] [7, 8] ... too far [0, -2] -> [-2, -4] ... too far, [0, 1] ... visited [1, 1] -> [2, 2], [1, -1] ...visited [-1 ,1] -> [0, 2], [-1, -1] ... too far [2, -2] -> [0, -4], [2, 1] [3, 1] -> [4, 2], [3, -1] ... visited [2, 2] -> [4, 4], [2, -1] [0, 2] -> [2, 4], [0, -1] ... visited [0, -4] -> [-4, -8] ... too far, [0, 1] ... visited [2, 1] -> [3, 2], [2, -1] [4, 2] -> [6, 4], [4, -1] [4, 4] -> [8, 8], [4, -1] ... in queue [2, -1] -> [1, -2], [2, 1] ... visited [2, 4] -> [6, 8], [2, -1] ... visited [3, 2] -> [5 , 4] -->> arrived -> 7 steps ''' ''' 1. try greedy -> can't pass tgt = 5 2. list out all the step until reach the tgt 3. speed up -> dont visit same nodes, dont go to \"too far\" nodes ''' visited = dict() q = collections.deque() q.append([0, 1]) visited[0] = set() visited[0].add(1) step = 0 while len(q) > 0: curSize = len(q) for i in range(0, curSize): pop = q.pop() pos, spd = pop[0], pop[1] if pos == tgt: return step nextSteps = [ [pos + spd, spd * 2], [pos, - 1 * spd // abs(spd)] ] for nextStep in nextSteps: nPos, nSpd = nextStep[0], nextStep[1] # check is too far node: if abs(nPos - tgt) <= tgt: # check visited if nPos not in visited or nSpd not in visited[nPos]: q.appendleft(nextStep) if nPos not in visited: visited[nPos] = set() visited[nPos].add(nSpd) step += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: def dfs(distance): if distance in dp: return dp[distance] position, speed, counter = 0, 1, 0 res = float('inf') arr = [(0)] while position < distance: position, speed, counter = position + speed, speed*2, counter+1 if position < distance: for x in arr: res = min(res, counter + 2 + dfs(distance - position + x) + dp[x]) else: res = min(res, counter + 1 + dfs(position - distance)) arr.append(position) dp[distance] = res return res position, speed, counter = 0, 1, 0 dp = {0:0} while position < target: position, speed, counter = position + speed, speed*2, counter+1 dp[position] = counter return dfs(target)
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, tgt: int) -> int: ''' shortest path -> bfs starting from [0, 1], how to reach tgt = 5? [0, 1] -> [1, 2], [0, -1] [1, 2] -> [3, 4], [1, -1] [0, -1] ->[-1, -2], [0, 1] ... visited [3, 4] -> [3, -1], [7, 8] [1,-1] -> [0, -2], [1, 1] [-1,-2]-> [-3,-4] ... too far, [-1,1] [3, -1] -> [2, -2], [3, 1] [7, 8] ... too far [0, -2] -> [-2, -4] ... too far, [0, 1] ... visited [1, 1] -> [2, 2], [1, -1] ...visited [-1 ,1] -> [0, 2], [-1, -1] ... too far [2, -2] -> [0, -4], [2, 1] [3, 1] -> [4, 2], [3, -1] ... visited [2, 2] -> [4, 4], [2, -1] [0, 2] -> [2, 4], [0, -1] ... visited [0, -4] -> [-4, -8] ... too far, [0, 1] ... visited [2, 1] -> [3, 2], [2, -1] [4, 2] -> [6, 4], [4, -1] [4, 4] -> [8, 8], [4, -1] ... in queue [2, -1] -> [1, -2], [2, 1] ... visited [2, 4] -> [6, 8], [2, -1] ... visited [3, 2] -> [5 , 4] -->> arrived -> 7 steps ''' ''' 1. try greedy -> can't pass tgt = 5 2. list out all the step until reach the tgt -> time: O(2 ^ (num of operations) ) 3. speed up -> dont visit same nodes, dont go to \"too far\" nodes 4. time complexity: pos range: -tgt ~ tgt, spd range: 1 ~ log(tgt) -> graph node number will be 2 * tgt * log(tgt) -> O(tgt * log(tgt) ) ''' visited = dict() q = collections.deque() q.append([0, 1]) visited[0] = set() visited[0].add(1) step = 0 while len(q) > 0: curSize = len(q) for i in range(0, curSize): pop = q.pop() pos, spd = pop[0], pop[1] if pos == tgt: return step nextSteps = [ [pos + spd, spd * 2], [pos, - 1 * spd // abs(spd)] ] for nextStep in nextSteps: nPos, nSpd = nextStep[0], nextStep[1] # check is too far node: if abs(nPos - tgt) <= tgt: # check visited if nPos not in visited or nSpd not in visited[nPos]: q.appendleft(nextStep) if nPos not in visited: visited[nPos] = set() visited[nPos].add(nSpd) step += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # position speed queue = [(0,1)] visited = set((0,1)) step = 0 q = 0 while len(queue) >q: step+=1 size = len(queue)-q for _ in range(size): x,v = queue[q] q+=1 ### keep on x_ = x+v v_ = v*2 if (x_, v_) not in visited and abs(x_)<2*target : queue.append((x_,v_)) visited.add((x_,v_)) if x_ == target: return step #### turn x_ = x if v>0: v_ = -1 else: v_ = 1 if (x_, v_) not in visited and abs(x_)<2*target : queue.append((x_,v_)) visited.add((x_,v_)) if x_ == target: return step
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: # position speed queue = [(0,1)] visited = set((0,1)) step = 0 q = 0 while len(queue) >q: step+=1 size = len(queue)-q for _ in range(size): x,v = queue[q] q+=1 ### keep on x_ = x+v v_ = v*2 # abs(x_)<2*target只是加速,不影响结果 if (x_, v_) not in visited and abs(x_)<2*target : queue.append((x_,v_)) visited.add((x_,v_)) if x_ == target: return step #### turn x_ = x if v>0: v_ = -1 else: v_ = 1 # abs(x_)<2*target只是加速,不影响结果 if (x_, v_) not in visited and abs(x_)<2*target : queue.append((x_,v_)) visited.add((x_,v_)) if x_ == target: return step
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, tgt: int) -> int: ''' shortest path -> bfs starting from [0, 1], how to reach tgt = 5? [0, 1] -> [1, 2], [0, -1] [1, 2] -> [3, 4], [1, -1] [0, -1] ->[-1, -2], [0, 1] ... visited [3, 4] -> [3, -1], [7, 8] [1,-1] -> [0, -2], [1, 1] [-1,-2]-> [-3,-4] ... too far, [-1,1] [3, -1] -> [2, -2], [3, 1] [7, 8] ... too far [0, -2] -> [-2, -4] ... too far, [0, 1] ... visited [1, 1] -> [2, 2], [1, -1] ...visited [-1 ,1] -> [0, 2], [-1, -1] ... too far [2, -2] -> [0, -4], [2, 1] [3, 1] -> [4, 2], [3, -1] ... visited [2, 2] -> [4, 4], [2, -1] [0, 2] -> [2, 4], [0, -1] ... visited [0, -4] -> [-4, -8] ... too far, [0, 1] ... visited [2, 1] -> [3, 2], [2, -1] [4, 2] -> [6, 4], [4, -1] [4, 4] -> [8, 8], [4, -1] ... in queue [2, -1] -> [1, -2], [2, 1] ... visited [2, 4] -> [6, 8], [2, -1] ... visited [3, 2] -> [5 , 4] -->> arrived -> 7 steps ''' ''' 1. try greedy -> can't pass tgt = 5 2. list out all the step until reach the tgt -> time: O(2 ^ (num of operations) ) 3. speed up -> dont visit same nodes, dont go to \"too far\" nodes ''' visited = dict() q = collections.deque() q.append([0, 1]) visited[0] = set() visited[0].add(1) step = 0 while len(q) > 0: curSize = len(q) for i in range(0, curSize): pop = q.pop() pos, spd = pop[0], pop[1] if pos == tgt: return step nextSteps = [ [pos + spd, spd * 2], [pos, - 1 * spd // abs(spd)] ] for nextStep in nextSteps: nPos, nSpd = nextStep[0], nextStep[1] # check is too far node: if abs(nPos - tgt) <= tgt: # check visited if nPos not in visited or nSpd not in visited[nPos]: q.appendleft(nextStep) if nPos not in visited: visited[nPos] = set() visited[nPos].add(nSpd) step += 1 return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: steps = 0 queue = deque([(0, 1)]) cache = {(0,1)} while queue: for _ in range(len(queue)): p, s = queue.popleft() if p == target: return steps p1,s1 = p+s, s*2 p2 = p s2 = -1 if s > 0 else 1 if -10000 <= p1 <= 10000 and (p1,s1) not in cache: cache.add((p1,s1)) queue.append((p1,s1)) if -10000 <= p2 <= 10000 and (p2,s2) not in cache: cache.add((p2,s2)) queue.append((p2,s2)) steps += 1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: # def racecar(self, target: int) -> int: # # position, speed # queue = deque([(0,1)]) # nsteps = -1 # while queue: # levelSize = len(queue) # nsteps += 1 # for _ in range(levelSize): # pos, speed = queue.popleft() # if pos == target: # return nsteps # # Always consider moving the car in the direction it is already going # queue.append( (pos+speed, speed*2) ) # # Only consider changing the direction of the car if one of the following conditions is true # if (pos>target and speed>0) or \\ # (pos<target and speed<0) or \\ # (pos+speed>target and speed>0) or \\ # (pos+speed<target and speed<0): # queue.append( (pos, -1 if speed>0 else 1) ) # return nsteps def __init__(self): self.dp = {0: 0} def racecar(self, t: int) -> int: if t in self.dp: return self.dp[t] n = t.bit_length() if 2**n - 1 == t: self.dp[t] = n else: # go pass the target, stop and turn back self.dp[t] = self.racecar(2**n-1-t) + n + 1 # Go as far as possible before pass target, stop and turn back for m in range(n-1): self.dp[t] = min(self.dp[t], self.racecar(t - 2**(n-1) + 1 + 2**m - 1) + (n - 1) + m + 2) return self.dp[t]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: been = set() steps = 0 queue = {(target, 1)} while queue: print(len(queue)) newQueue = set() for pos, speed in queue: if pos == 0: return steps been.add((pos, speed)) nextStatus = (abs(pos - speed), -speed * 2 if speed > pos else speed * 2) if nextStatus[0] < target * 2 and nextStatus not in been: newQueue.add(nextStatus) nextStatus = (pos, -1 if speed > 0 else 1) if nextStatus[0] < target * 2 and nextStatus not in been: newQueue.add(nextStatus) steps += 1 queue = newQueue
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length()+1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2*barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] < steps: continue for k in range(K+1): walk = (1<<k)-1 steps2, targ2 = steps+k+1, walk - targ if walk == targ: steps2 -= 1 if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] < steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, t: int) -> int: q=[(0,1,0)] seen={} while q: c,s,step=q.pop(0) if (c,s) in seen: continue else: seen[(c,s)]=step if c==t: return step step+=1 # A c1=c+s s1=s*2 if abs(c+s-t) < t and (c1,s1) not in seen: q.append((c1,s1,step)) # R s2=-1 if s>0 else 1 if abs(c-t) < t and (c,s2) not in seen: q.append((c,s2,step)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: import heapq K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: st = [(0, 1, '')] visited = set() while st: a = st.pop(0) if a[0] == target: return len(a[2]) # put a 'A' if 0 <= a[0] + a[1] < 2 * target and (a[0] + a[1], a[1] * 2) not in visited: st.append((a[0] + a[1], a[1] * 2, a[2] + 'A')) visited.add((a[0] + a[1], a[1] * 2)) # put a 'R' if a[0] >= 0 and (a[0], -1 if a[1] > 0 else 1) not in visited: st.append((a[0], -1 if a[1] > 0 else 1, a[2] + 'R')) visited.add((a[0], -1 if a[1] > 0 else 1)) return -1
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) #if dist[targ] < steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution(object): def racecar(self, target): K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target): K = target.bit_length() + 1 barrier = 2**K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target): K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: steps, targ = heapq.heappop(pq) if dist[targ] > steps: continue for k in range(K+1): walk = (1 << k) - 1 steps2, targ2 = steps + k + 1, walk - targ if walk == targ: steps2 -= 1 #No \"R\" command if already exact if abs(targ2) <= barrier and steps2 < dist[targ2]: heapq.heappush(pq, (steps2, targ2)) dist[targ2] = steps2 return dist[0]
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
class Solution: def racecar(self, target: int) -> int: boundary = 2*target+1 forw_stat = [target*3] * boundary back_stat = [target*3] * boundary actions = [] _s = 1 queue = [] while True: _jump = 2**_s - 1 if _jump >= boundary: break actions.append((_jump, _s)) # jump, step actions.append((-_jump, _s)) queue.append((_s, _jump, 1)) forw_stat[_jump] = _s _s += 1 # print(actions) # -- import heapq heapq.heapify(queue) while len(queue)>0: step, posi, is_forw = heapq.heappop(queue) # -- for _jump, _step in actions: if _jump * is_forw > 0: next_step, next_posi, next_is_forw = (step+_step+2, posi+_jump, is_forw) else: next_step, next_posi, next_is_forw = (step+_step+1, posi+_jump, -is_forw) # -- if next_posi<0 or next_posi>=boundary: continue cur_stat = forw_stat if next_is_forw==1 else back_stat if next_step < cur_stat[next_posi]: cur_stat[next_posi] = next_step heapq.heappush(queue, (next_step, next_posi, next_is_forw)) # -- return min(forw_stat[target], back_stat[target])
Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, speed *= 2. When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.) For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1. Now for some target position, say the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0->1->3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0->1->3->7->7->6.   Note: 1 <= target <= 10000.
from collections import deque class Solution: def racecar(self, target: int) -> int: visited = set() q = deque([(0,1,0)]) while q: pos, sp, d = q.popleft() #print(pos, q) if pos==target: return d if (pos, sp) in visited: continue visited.add((pos, sp)) if abs(sp)>target: # in these cases, must turn. q.append((pos, -1*(sp//abs(sp)), d+1)) else: # can keep goint or turn. q.append((pos+sp, sp*2, d+1)) q.append((pos, -1*(sp//abs(sp)), d+1))
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
from collections import deque class Solution: def longestSubarray(self, nums, limit): maxQ, minQ = deque(), deque() i = 0 res = 0 for j, val in enumerate(nums): while maxQ and val > maxQ[-1]: maxQ.pop() while minQ and val < minQ[-1]: minQ.pop() maxQ.append(val) minQ.append(val) if maxQ[0] - minQ[0] > limit: if maxQ[0] == nums[i]: maxQ.popleft() if minQ[0] == nums[i]: minQ.popleft() i += 1 res = max(res, j-i+1) return res from collections import deque class Solution: def longestSubarray(self, nums, limit): maxQ, minQ = deque(), deque() i = 0 for val in nums: while maxQ and val > maxQ[-1]: maxQ.pop() while minQ and val < minQ[-1]: minQ.pop() maxQ.append(val) minQ.append(val) if maxQ[0] - minQ[0] > limit: if maxQ[0] == nums[i]: maxQ.popleft() if minQ[0] == nums[i]: minQ.popleft() i += 1 return len(nums) - i
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minHeap,maxHeap=[],[] left=maxLen=0 for right in range(len(nums)): heappush(minHeap,(nums[right],right)) heappush(maxHeap,(-nums[right],right)) while nums[right]-minHeap[0][0]>limit: left=max(left,(heappop(minHeap)[1])+1) while -maxHeap[0][0]-nums[right]>limit: left=max(left,(heappop(maxHeap)[1])+1) maxLen=max(maxLen,right-left+1) return maxLen
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: if len(nums) < 2: return 1 longestSize = 1 left = 0 lo_q, hi_q = [], [] heapq.heappush(lo_q, (nums[0], 0)) heapq.heappush(hi_q, (-nums[0], 0)) for idx in range(1, len(nums)): if lo_q and nums[idx] < lo_q[0][0]: lo_q = [] elif hi_q and -nums[idx] < hi_q[0][0]: hi_q = [] heapq.heappush(lo_q, (nums[idx], idx)) heapq.heappush(hi_q, (-nums[idx], idx)) while lo_q and abs(nums[idx] - lo_q[0][0]) > limit: left = max(left, heapq.heappop(lo_q)[1] + 1) while hi_q and abs(nums[idx] + hi_q[0][0]) > limit: left = max(left, heapq.heappop(hi_q)[1] + 1) longestSize = max(longestSize, idx - left + 1) return longestSize
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: min_heap = [] max_heap = [] start = 0 best = 0 for idx, val in enumerate(nums): heappush(min_heap, (val, idx)) heappush(max_heap, (-val, idx)) while start < idx and abs(min_heap[0][0] + max_heap[0][0]) > limit: start += 1 while min_heap[0][1] < start: heappop(min_heap) while max_heap[0][1] < start: heappop(max_heap) best = max(best, idx - start + 1) return best
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
from heapq import * class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minH = [] maxH = [] l = 0 ans = 0 for r, n in enumerate(nums): heappush(minH, (n,r)) heappush(maxH, (-n,r)) while -maxH[0][0] - minH[0][0] > limit: l = min(maxH[0][1], minH[0][1]) + 1 while maxH[0][1] < l: heappop(maxH) while minH[0][1] < l: heappop(minH) # print(l, r, maxH, minH) ans = max(ans, r-l+1) return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
# https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/721619/Python-Rust-Sliding-Window-and-Deque ''' The problem description states that we need to find the window with the largest size that has max-min<=limit This is clearly a sliding window problem. The brute force solution is to start from each index, keep on expanding, and once the max-min is larger than limit, we break. O(n^2) Can we do better? Well, we can actually use a classic technique in sliding window problems where we keep on expanding the window from the right until the window is no longer valid. Once the window is invalid we keep on contracting it from the left until it becomes valid again. (Just like in the famous \"Longest Substring Without Repeating Characters\" problem. Every iteration we need to answer the question, what is our current min and max? this leads us to using two heaps where one of them is a min heap and the other is a max heap. Every iteration we push the new number to both heaps and then keep on popping from the min and max heaps until we're sure that we've maintained the invariant maxHeap[0] - minHeap[0] <= limit. We do O(N) pushes and pops from the heaps and each push/pop is O(logN) so we end up with an O(NlogN) solution. Here is the code: ''' class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minHeap, maxHeap = [], [] left = maxLen = 0 for right, num in enumerate(nums): heappush(minHeap, (num, right)) heappush(maxHeap, (-num, right)) while num - minHeap[0][0] > limit: left = max(left, heappop(minHeap)[1] + 1) while -maxHeap[0][0] - num > limit: left = max(left, heappop(maxHeap)[1] + 1) maxLen = max(maxLen, right - left + 1) return maxLen
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: import heapq mnq, mxq = [], [] res = 0 left = -1 for right, num in enumerate(nums): heapq.heappush(mnq, (num, right)) heapq.heappush(mxq, (-num, right)) while -mxq[0][0] - mnq[0][0] > limit: left = min(mnq[0][1], mxq[0][1]) while mxq[0][1] <= left: heapq.heappop(mxq) while mnq[0][1] <= left: heapq.heappop(mnq) res = max(res, right - left) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: n = len(nums) minh = [] maxh = [] start = 0 ans = 0 deleted = set() for end in range(n): x = nums[end] heappush(minh, (x, end)) heappush(maxh, (-x, end)) while minh and minh[0][1] in deleted: heappop(minh) while maxh and maxh[0][1] in deleted: heappop(maxh) while minh and maxh and -maxh[0][0] - minh[0][0] > limit and start <= end: deleted.add(start) start += 1 while minh and minh[0][1] in deleted: heappop(minh) while maxh and maxh[0][1] in deleted: heappop(maxh) ans = max(ans, end - start + 1) return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: min_heap, max_heap = deque([0]), deque([0]) res = 1 far = -1 #stores the index of the position where the array becomes invalid for i in range(1, len(nums)) : while min_heap and nums[min_heap[-1]] >nums[i]: min_heap.pop() while max_heap and nums[max_heap[-1]] <nums[i]: max_heap.pop() while min_heap and abs(nums[min_heap[0]] - nums[i]) >limit: far = max(far,min_heap.popleft()) while max_heap and abs(nums[max_heap[0]] - nums[i]) >limit: far = max(far,max_heap.popleft()) res = max(res,i-far) min_heap.append(i) max_heap.append(i) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: #naive method in n2 #keep track of min and max #sliding window: only when exceed limit then contract window if not nums: return 0 minDeque = collections.deque() maxDeque = collections.deque() maxlength = 0 left = 0 right = 0 while right< len(nums):#not equal sign while maxDeque and nums[right] > nums[maxDeque[-1]]: maxDeque.pop() #decreasign deque maxDeque.append(right) while minDeque and nums[right] < nums[minDeque[-1]]: minDeque.pop() minDeque.append(right) #it won't be empty, because the \"curr\" element will always be valid while abs(nums[maxDeque[0]] - nums[minDeque[0]]) >limit: if maxDeque[0] == left: maxDeque.popleft() if minDeque[0] == left: minDeque.popleft() left += 1 maxlength = max(maxlength, right-left+1) right += 1 return maxlength
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minHeap = [] maxHeap = [] l = 0 maxSize = 0 for r,num in enumerate(nums): heappush(minHeap, (num, r)) heappush(maxHeap, (-num, r)) minElement, minIndex = minHeap[0] maxElement, maxIndex = maxHeap[0] maxElement = -maxElement while maxElement - minElement > limit: l+=1 while minHeap[0][1] < l: heappop(minHeap) while maxHeap[0][1] < l: heappop(maxHeap) minElement, minIndex = minHeap[0] maxElement, maxIndex = maxHeap[0] maxElement = -maxElement curSize = r-l+1 maxSize = max(curSize, maxSize) return maxSize
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: import heapq mnq, mxq = [], [] res = 0 left = 0 for right, num in enumerate(nums): heapq.heappush(mnq, (num, right)) heapq.heappush(mxq, (-num, right)) while -mxq[0][0] - mnq[0][0] > limit: left = min(mnq[0][1], mxq[0][1]) + 1 while mxq[0][1] < left: heapq.heappop(mxq) while mnq[0][1] < left: heapq.heappop(mnq) res = max(res, right - left + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: maxHeap = [] minHeap = [] ans = 0 i = 0 for j in range(len(nums)): heapq.heappush(maxHeap, (-nums[j], j)) heapq.heappush(minHeap, (nums[j], j)) while -maxHeap[0][0] - minHeap[0][0] > limit: i = min(maxHeap[0][1], minHeap[0][1]) + 1 while maxHeap[0][1] < i: heapq.heappop(maxHeap) while minHeap[0][1] < i: heapq.heappop(minHeap) ans = max(ans, j - i +1) return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import collections class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minDeque = collections.deque() maxDeque = collections.deque() start = end = 0 ans = 0 while end < len(nums): # print(start, end, ans) n = nums[end] while len(minDeque)>0 and nums[minDeque[-1]]>=n: minDeque.pop() minDeque.append(end) while len(maxDeque)>0 and nums[maxDeque[-1]]<=n: maxDeque.pop() maxDeque.append(end) if (nums[maxDeque[0]] - nums[minDeque[0]]) > limit: start+=1 while len(minDeque)>0 and minDeque[0]<start: minDeque.popleft() while len(maxDeque)>0 and maxDeque[0]<start: maxDeque.popleft() else: ans = max(ans, (end-start)+1) end+=1 return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import heapq class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minheap,maxheap = [],[] start = 0 res = 0 for j,elem in enumerate(nums): heapq.heappush(minheap,(elem,j)) heapq.heappush(maxheap,(-elem,j)) while - maxheap[0][0] - minheap[0][0] > limit: start = min(minheap[0][1],maxheap[0][1]) + 1 while maxheap[0][1]<start: heapq.heappop(maxheap) while minheap[0][1]< start: heapq.heappop(minheap) res = max(res,j-start+1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: # we have to maintain two min/max heaps with both value and index # slide right if subarray is still valid # slide left until subarray is valid again: if min/max value's index is earlier than left, then pop it out n = len(nums) i, j, ans = 0, 0, 0 min_heap, max_heap = [], [] heapq.heapify(min_heap) heapq.heapify(max_heap) while i <= j < n: heapq.heappush(min_heap, (nums[j], j)) heapq.heappush(max_heap, (-nums[j], j)) while i <= j < n and -max_heap[0][0]-min_heap[0][0] > limit: i += 1 while min_heap and min_heap[0][1] < i: heapq.heappop(min_heap) while max_heap and max_heap[0][1] < i: heapq.heappop(max_heap) ans = max(ans, j-i+1) j += 1 return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import heapq # minMaxQueue: # max 4 5 # min 4 3 3 2 # queue: [1, 6, 8, 2, 2] class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: longest = 0 mins = [] maxs = [] start = 0 i = 0 while i < len(nums): x = nums[i] heapq.heappush(mins, (x, i)) heapq.heappush(maxs, (-x, i)) currMin, currMax = mins[0][0], -(maxs[0][0]) while mins and maxs and currMax - currMin > limit: start += 1 while mins[0][1] < start: heapq.heappop(mins) while maxs[0][1] < start: heapq.heappop(maxs) currMin, currMax = mins[0][0], -(maxs[0][0]) longest = max(longest, i - start + 1) i += 1 return longest
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: minheap, maxheap = [], [] res = 0 i = 0 for j,n in enumerate(nums): heapq.heappush(minheap, (n, j)) heapq.heappush(maxheap, (-n, j)) while -maxheap[0][0] - minheap[0][0] > limit: i = min(maxheap[0][1], minheap[0][1]) + 1 while maxheap[0][1] < i: heapq.heappop(maxheap) while minheap[0][1] < i: heapq.heappop(minheap) res = max(res, j - i + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import heapq # minMaxQueue: # max 4 5 # min 4 3 3 2 # queue: [1, 6, 8, 2, 2] class Solution: # O(N) time | O(N) space def longestSubarray(self, nums: List[int], limit: int) -> int: longest = 0 mins = [] maxs = [] start = 0 i = 0 while i < len(nums): # O(N) x = nums[i] heapq.heappush(mins, (x, i)) # O() heapq.heappush(maxs, (-x, i)) # O() currMin, currMax = mins[0][0], -(maxs[0][0]) while mins and maxs and currMax - currMin > limit: start += 1 while mins[0][1] < start: heapq.heappop(mins) while maxs[0][1] < start: heapq.heappop(maxs) currMin, currMax = mins[0][0], -(maxs[0][0]) longest = max(longest, i - start + 1) i += 1 return longest
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: maxq, minq = [], [] res = i = 0 for j, num in enumerate(nums): heappush(maxq, (-num, j)) heappush(minq, (num, j)) while -maxq[0][0] - minq[0][0] > limit: i = min(maxq[0][1], minq[0][1]) + 1 while maxq[0][1] < i: heappop(maxq) while minq[0][1] < i: heappop(minq) res = max(res, j - i + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, A, limit): M = collections.deque() m = collections.deque() i = 0 for a in A: # a = A[j], A[i:j] is a candidate # whose lenngth is j-i # whose max is M[0] and min is m[0] # if its max - min > limit we shrink the window # if max or min changed we pop M and m from the left while M and a > M[-1]: M.pop() while m and a < m[-1]: m.pop() M.append(a) m.append(a) if M[0] - m[0] > limit: if M[0] == A[i]: M.popleft() if m[0] == A[i]: m.popleft() i += 1 return len(A) - i
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
from collections import deque class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: if not nums or len(nums) == 0: return 0 minDeque = deque() maxDeque = deque() left = 0 right = 0 result = 0 while right < len(nums): # Maintain minDeque while minDeque and nums[right] < nums[minDeque[-1]]: minDeque.pop() while maxDeque and nums[right] > nums[maxDeque[-1]]: maxDeque.pop() minDeque.append(right) maxDeque.append(right) while nums[maxDeque[0]] - nums[minDeque[0]] > limit: while maxDeque[0] <= left: maxDeque.popleft() while minDeque[0] <= left: minDeque.popleft() left += 1 result = max(result, right - left + 1) right += 1 return result
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: if not nums: return 0 n = len(nums) i = j = 0 curr_max = curr_min = nums[0] maxes = [(-curr_max, 0)] mins = [(curr_min, 0)] best = 0 while i <= j < n: # print(\"i\", i, \"j\", j, \"max:\", -maxes[0][0], \"at idx\", maxes[0][1], \"min:\", mins[0][0], \"at idx\", mins[0][1]) # advance j until difference exceeds limit if abs(-maxes[0][0] - mins[0][0]) <= limit: best = max(best, j-i+1) j += 1 if j < n: heapq.heappush(maxes, (-nums[j], j)) heapq.heappush(mins, (nums[j], j)) else: i += 1 # lazily remove all values outside of the window while not i <= maxes[0][1] <= j: heapq.heappop(maxes) while not i <= mins[0][1] <= j: heapq.heappop(mins) return best
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
import heapq class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: ans = 1 i = j = 0 minHeap = [(nums[0], 0)] maxHeap = [(-nums[0], 0)] while(j < len(nums)): while(minHeap[0][1] < i): heapq.heappop(minHeap) while(maxHeap[0][1] < i): heapq.heappop(maxHeap) if(-maxHeap[0][0]-minHeap[0][0] > limit): i += 1 else: j += 1 ans = max(ans, j-i) if(j < len(nums)): heapq.heappush(minHeap, (nums[j], j)) heapq.heappush(maxHeap, (-nums[j], j)) return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: if len(nums)<=1: return len(nums) queue = [nums[0]] small = queue[0] large = queue[0] ans = 1 for i in range(1, len(nums)): if abs(nums[i]-small)<=limit and abs(nums[i]-large)<=limit: queue.append(nums[i]) small = min(small, nums[i]) large = max(large, nums[i]) ans = max(ans, len(queue)) else: if ans>len(nums)//2: break while queue and not(abs(nums[i]-small)<=limit and abs(nums[i]-large)<=limit): queue.pop(0) if queue: small = min(queue) large = max(queue) else: break if queue: queue.append(nums[i]) small = min(queue) large = max(queue) else: queue = [nums[i]] small = nums[i] large = nums[i] return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: # def longestSubarray(self, nums: List[int], limit: int) -> int: # start=0 # end=1 # result=1 # while end<len(nums): # tmp=nums[end] # flag=0 # for i in range(start,end): # if abs(nums[i]-tmp)>limit: # flag=1 # start=i # if flag==0: # if end-start+1>result: # result=end-start+1 # end+=1 # else: # start+=1 # return result def longestSubarray(self, A, limit): maxq, minq = [], [] res = i = 0 for j, a in enumerate(A): heapq.heappush(maxq, [-a, j]) heapq.heappush(minq, [a, j]) while -maxq[0][0] - minq[0][0] > limit: i = min(maxq[0][1], minq[0][1]) + 1 while maxq[0][1] < i: heapq.heappop(maxq) while minq[0][1] < i: heapq.heappop(minq) res = max(res, j - i + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
# lame implementation of random removal in min/max heaps, but i saw # phorum solutions about monotonic queues, quite interesting! class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: n = len(nums) minh = [] maxh = [] start = 0 ans = 0 deleted = set() for end in range(n): x = nums[end] heappush(minh, (x, end)) heappush(maxh, (-x, end)) while minh and minh[0][1] in deleted: heappop(minh) while maxh and maxh[0][1] in deleted: heappop(maxh) while minh and maxh and -maxh[0][0] - minh[0][0] > limit and start <= end: deleted.add(start) start += 1 while minh and minh[0][1] in deleted: heappop(minh) while maxh and maxh[0][1] in deleted: heappop(maxh) ans = max(ans, end - start + 1) return ans
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, A, limit): maxq, minq = [], [] res = i = 0 for j, a in enumerate(A): heapq.heappush(maxq, [-a, j]) heapq.heappush(minq, [a, j]) while -maxq[0][0] - minq[0][0] > limit: i = min(maxq[0][1], minq[0][1]) + 1 while maxq[0][1] < i: heapq.heappop(maxq) while minq[0][1] < i: heapq.heappop(minq) res = max(res, j - i + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: # HEAP SLIDING WINDOW SOLUTION max_heap, min_heap = [], [] res = 0 l = 0 for r, a in enumerate(nums): heapq.heappush(max_heap, [-a, r]) heapq.heappush(min_heap, [a, r]) while -max_heap[0][0] - min_heap[0][0] > limit: # we need to kick all the elments before left pointer while max_heap[0][1] <= l: heapq.heappop(max_heap) while min_heap[0][1] <= l: heapq.heappop(min_heap) l += 1 res = max(res, r - l + 1) return res
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, A: List[int], limit: int) -> int: maxd = collections.deque() mind = collections.deque() i = 0 for a in A: while maxd and a > maxd[-1]: maxd.pop() while mind and a < mind[-1]: mind.pop() maxd.append(a) mind.append(a) if maxd[0] - mind[0] > limit: if maxd[0] == A[i]: maxd.popleft() if mind[0] == A[i]: mind.popleft() i += 1 return len(A) - i
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.   Example 1: Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. Example 2: Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. Example 3: Input: nums = [4,2,2,2,4,4,2,2], limit = 0 Output: 3   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 0 <= limit <= 10^9
class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: # HEAP SLIDING WINDOW SOLUTION max_heap, min_heap = [], [] res = 0 l = 0 for r, a in enumerate(nums): heapq.heappush(max_heap, [-a, r]) heapq.heappush(min_heap, [a, r]) while -max_heap[0][0] - min_heap[0][0] > limit: while max_heap[0][1] <= l: heapq.heappop(max_heap) while min_heap[0][1] <= l: heapq.heappop(min_heap) l += 1 res = max(res, r - l + 1) return res