inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
if not stations:
return -1
fdelta = startFuel-stations[0][0]
if fdelta < 0:
return -1
curr = [fdelta + stations[0][1], fdelta]
for i, sta in enumerate(stations[1:]):
treck = sta[0] - stations[i][0]
leftover = curr[0]-treck
if leftover < 0:
return -1
nex = [leftover + sta[1], leftover]
for j, f in enumerate(curr[1:]):
leftover = curr[j+1] - treck
if leftover < 0:
break
else:
nex[-1] = max(nex[-1], leftover+sta[1])
nex.append(leftover)
curr = nex
leftover = target - stations[-1][0]
while curr and curr[-1] < leftover:
curr.pop()
return len(stations) - len(curr) + 1 if curr else -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
import heapq
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
stops = 0
max_gas_heap = []
can_drive_to = startFuel
i = 0
while can_drive_to < target:
# push stations to heap
while i < len(stations) and stations[i][0] <= can_drive_to:
heapq.heappush(max_gas_heap, -stations[i][1])
i += 1
if not max_gas_heap:
return -1
can_drive_to -= heapq.heappop(max_gas_heap)
stops += 1
return stops
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
n = len(stations)
dp = [0]*(n+1)
dp[0] = startFuel
for i in range(1, n+1):
for j in range(i, 0, -1):
if dp[j-1] >= stations[i-1][0]:
# use station i-1
dp[j] = max(dp[j], dp[j-1] + stations[i-1][1])
for i in range(1, n+1):
if dp[i] >= target:
return i
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
import heapq
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
point=0
level=0
gas=startFuel
if gas>=target:
return level
heap=[]
stations.append([target+1,float('inf')])
for pos,gas_add in stations:
if gas>=pos:
heapq.heappush(heap,-gas_add)
else:
while heap:
gasmin=heapq.heappop(heap)
gas-=gasmin
level+=1
if gas>=target:
return level
if gas>=pos:
heapq.heappush(heap,-gas_add)
break
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
if startFuel < target and not stations:
return -1
dp = [startFuel] + [0] * len(stations)
for i, val in enumerate(stations):
for t in range(i, -1, -1):
if dp[t] >= val[0]:
dp[t+1] = max(dp[t+1], dp[t] + val[1])
for i, d in enumerate(dp):
if d >= target:
return i
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
# if startFuel >= target:
# return 0
# @lru_cache(maxsize=None)
# def helper(startIdx, litre, target):
# if litre >= target:
# return 0
# result = float('inf')
# for idx in range(startIdx + 1, len(stations)):
# if startIdx == -1:
# n_miles = stations[idx][0]
# else:
# n_miles = stations[idx][0] - stations[startIdx][0]
# remain = litre - n_miles
# if remain >= 0:
# result = min(result, 1 + helper(idx, remain + stations[idx][1], target - n_miles))
# return result
# result = helper(-1, startFuel, target)
# return -1 if result == float('inf') else result
#-----------------------------------------------------------------------------
# if startFuel >= target:
# return 0
# heap = []
# idx = n_stations = 0
# maxDistance = startFuel
# while maxDistance < target:
# while idx < len(stations) and stations[idx][0] <=maxDistance:
# heapq.heappush(heap, -stations[idx][1])
# idx += 1
# if not heap:
# return -1
# maxDistance += (-heapq.heappop(heap))
# n_stations += 1
# return n_stations
#-----------------------------------------------------------------------------
# if startFuel >= target:
# return 0
# length = len(stations)
# dp = [[0] * (1 + length) for _ in range(1 + length)]
# for i in range(1 + length):
# dp[i][0] = startFuel
# result = float('inf')
# for i in range(1 + length):
# for j in range(1, i + 1):
# if j <= i - 1:
# dp[i][j] = max(dp[i][j], dp[i - 1][j])
# if dp[i - 1][j - 1] >= stations[i - 1][0]:
# dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + stations[i - 1][1])
# if dp[i][j] >= target:
# result = min(result, j)
# return -1 if result == float('inf') else result
#-----------------------------------------------------------------------------
if startFuel >= target:
return 0
length = len(stations)
dp = [startFuel] + [0] * length
result = float('inf')
for i in range(1 + length):
for j in range(i, 0, -1):
if dp[j - 1] >= stations[i - 1][0]:
dp[j] = max(dp[j], dp[j - 1] + stations[i - 1][1])
if dp[j] >= target:
result = min(result, j)
return -1 if result == float('inf') else result
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target : return 0
pq = []
minStops = i = 0
curr = startFuel
while curr < target:
while i < len(stations) and curr >= stations[i][0]:
heapq.heappush(pq, -stations[i][1])
i += 1
if not pq: return -1
curr += -heapq.heappop(pq)
minStops +=1
return minStops
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
from heapq import heapify, heappop, heappush
dis = startFuel
heap = []
stations = stations[::-1]
while stations and stations[-1][0] <= dis:
s = stations.pop()
heap.append((-s[1], s[0]))
heapify(heap)
stops = 0
while heap:
most_fuel = heappop(heap)
stops += 1
dis += (-most_fuel[0])
if dis >= target:
return stops
while stations and stations[-1][0] <= dis:
s = stations.pop()
heappush(heap, (-s[1], s[0]))
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target, startFuel, stations):
stations.append([target, 0])
stations.sort(reverse=True)
curr, tank = 0, startFuel
ans = 0
refuels = []
while curr + tank < target:
pos, gas = stations.pop()
if pos <= curr+tank:
heapq.heappush(refuels, -gas)
else:
curr += tank
tank = 0
while curr+tank < pos and refuels:
ans += 1
tank -= heapq.heappop(refuels)
if curr+tank < pos:
return -1
heapq.heappush(refuels, -gas)
return ans
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
q=[]
extent = startFuel
ans = 0
for i in range(len(stations)):
if extent>=target:
return ans
loc, fuel = stations[i]
while q and loc>extent :
extent += -heapq.heappop(q)
ans+=1
if loc>extent:
return -1
heapq.heappush(q, -fuel)
while q and extent<target:
extent+=-heapq.heappop(q)
ans+=1
if extent>=target:
return ans
else:
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
q=[]
extent = startFuel
ans = 0
for i in range(len(stations)):
if extent>=target:
return ans
loc, fuel = stations[i]
print((i, loc, extent))
while q and loc>extent :
extent += -heapq.heappop(q)
ans+=1
if loc>extent:
return -1
heapq.heappush(q, -fuel)
while q and extent<target:
extent+=-heapq.heappop(q)
ans+=1
if extent>=target:
return ans
else:
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
pq = []
idx = 0
cur = startFuel
res = 0
while cur < target:
while idx < len(stations) and cur >= stations[idx][0]:
heapq.heappush(pq, -stations[idx][1])
idx += 1
if not pq: return -1
cur -= heapq.heappop(pq)
res += 1
return res
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
if not stations:
return -1
steps = 0
i = 0
pq = []
while startFuel < target:
while i < len(stations) and stations[i][0] <= startFuel:
heapq.heappush(pq, -stations[i][1])
i += 1
if not pq:
return -1
else:
startFuel -= heapq.heappop(pq)
steps += 1
return steps
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
heap = []
queue = deque()
i = 0
num_stations = 0
while startFuel < target:
while i < len(stations) and startFuel >= stations[i][0]:
heapq.heappush(heap, (-stations[i][1]))
i += 1
if not heap:
return -1
next_fuel = heapq.heappop(heap)
startFuel -= next_fuel
num_stations += 1
return num_stations
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
N = len(stations)
# We will try different number of stops. Initial state num_stops=0.
# memo[num_stations] = max_mile we can reach if only available
# first num_stations, and we make exactly num_stops
prev_memo = [startFuel] * (N + 1)
for num_stops in range(1, N + 1):
memo = [-1] * (N + 1)
a = -1
for num_stations in range(num_stops, N + 1):
station_mile, station_fuel = stations[num_stations - 1]
# a = memo[num_stations - 1]
# Optimization: a is available from previous loop,
# so don't need to access it from memo[]
b = prev_memo[num_stations - 1]
if b >= station_mile: # Check if we can reach this station
a = max(a, b + station_fuel)
if a != -1:
memo[num_stations] = a
# if memo[N] >= target:
if a >= target:
return num_stops
prev_memo = memo
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
N = len(stations)
# We will try different number of stops. Initial state num_stops=0.
# memo[num_stations] = max_mile we can reach if only available
# first num_stations, and we make exactly num_stops
prev_memo = [startFuel] * (N + 1)
for num_stops in range(1, N + 1):
memo = [-1] * (N + 1)
a = -1
for num_stations in range(num_stops, N + 1):
station_mile, station_fuel = stations[num_stations - 1]
# a = memo[num_stations - 1]
# Optimization: a is available from previous loop,
# so don't need to access it from memo[]
b = prev_memo[num_stations - 1]
if b >= station_mile: # Check if we can reach this station
a = max(a, b + station_fuel)
memo[num_stations] = a
# if memo[N] >= target:
if a >= target:
return num_stops
prev_memo = memo
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel>=target:
return 0
stations.sort(reverse=True)
fuel=startFuel
heap=[]
out=0
while stations:
while stations and fuel>=stations[-1][0]:
t,val=stations.pop()
if t>=target:
return out
heapq.heappush(heap,-val)
if heap:
fuel-=heapq.heappop(heap)
out+=1
if fuel>=target:
return out
else:
break
while heap and fuel<target:
fuel-=heapq.heappop(heap)
out+=1
if fuel<target:
return -1
return out
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
N = len(stations)
# We will try different number of stops. Initial state num_stops=0.
# memo[num_stations] = max_mile we can reach if only available
# first num_stations, and we make exactly num_stops
prev_memo = [startFuel] * (N + 1)
for num_stops in range(1, N + 1):
memo = [-1] * (N + 1)
a = -1
for num_stations in range(num_stops, N + 1):
station_mile, station_fuel = stations[num_stations - 1]
# a = memo[num_stations - 1]
# Optimization: a is available from previous loop,
# so don't need to access it from memo[]
b = prev_memo[num_stations - 1]
if b >= station_mile: # Check if we can reach this station
b += station_fuel
a = max(a, b)
if a != -1:
memo[num_stations] = a
# if memo[N] >= target:
if a >= target:
return num_stops
prev_memo = memo
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if target <= startFuel:
return 0
dpRefuels = [-1] * len(stations)
for i in range(len(stations)):
if stations[i][0] <= startFuel:
dpRefuels[i] = stations[i][1] + startFuel
if dpRefuels[i] >= target:
return 1
for k in range(1, len(stations)):
# use k stations to reach target
maxPrevFuel = dpRefuels[k-1]
for i in range(k, len(stations)):
# the i-th station would be the k-th refuel at each iteration
temp = max(maxPrevFuel, dpRefuels[i])
if maxPrevFuel >= stations[i][0]:
dpRefuels[i] = maxPrevFuel + stations[i][1]
if dpRefuels[i] >= target:
return k + 1
maxPrevFuel = temp
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
fuel = startFuel
del startFuel
i = 0
while target > fuel:
target -= fuel
stations = [[dist-fuel, gas] for dist, gas in stations]
try:
j, fuel = max([[j, gas]
for j, (dist, gas)
in enumerate(stations)
if dist <= 0],
key=lambda stop: stop[1])
except ValueError:
return -1
if fuel == 0:
return -1
stations[j][1] = 0
i += 1
return i
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if target <= startFuel:
return 0
dpRefuels = [[-1] * len(stations) for _ in range(len(stations))]
for i in range(len(stations)):
if stations[i][0] <= startFuel:
dpRefuels[0][i] = stations[i][1] + startFuel
if dpRefuels[0][i] >= target:
return 1
for k in range(1, len(stations)):
# use k stations to reach target
maxPrevFuel = dpRefuels[k-1][k-1]
for i in range(k, len(stations)):
# the i-th station would be the k-th refuel at each iteration
if maxPrevFuel >= stations[i][0]:
dpRefuels[k][i] = maxPrevFuel + stations[i][1]
if dpRefuels[k][i] >= target:
return k + 1
maxPrevFuel = max(maxPrevFuel, dpRefuels[k-1][i])
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target: return 0
if not stations: return -1
data = []
for k in range(len(stations)):
data.append([stations[k][0]-(stations[k-1][0] if k > 0 else 0), stations[k][1]])
data.append([target-stations[-1][0],0])
# data is a list of [how far you have to go to reach station x from previous station, how much gas you get at station x]
# we add a \"station\" at the target with 0 gas... we want to see if we can reach this spot
# let's check if we made all stops, we could make it
tot = startFuel
for dist,gas in data:
tot -= dist
if tot < 0: return -1
tot += gas
N = len(data)
# maxFuel represents how much fuel you could have at this station
maxFuel = [float('-inf')] * N
# let's start with 0 stops
tot = startFuel
for k in range(N):
dist,_ = data[k]
tot -= dist
if tot < 0: break
maxFuel[k] = tot
#print('after 0 stops',maxFuel)
# let's do 1 stop separately as well
nextMaxFuel = [float('-inf')] * N
nextMaxFuel[0] = maxFuel[0] + data[0][1]
for k in range(1,N):
dist,gas = data[k]
if maxFuel[k] != float('-inf'):
nextMaxFuel[k] = maxFuel[k]+gas
if nextMaxFuel[k-1] >= dist:
nextMaxFuel[k] = max(nextMaxFuel[k], nextMaxFuel[k-1]-dist)
if nextMaxFuel[k] == float('-inf'):
break
if nextMaxFuel[-1] >= 0: return 1
maxFuel = nextMaxFuel
#print('after 1 stop',maxFuel)
for nStops in range(2, N+1):
nextMaxFuel = [float('-inf')] * N
for k in range(nStops-1, N):
dist,gas = data[k]
if maxFuel[k-1] != float('-inf') and maxFuel[k-1] >= dist: # i.e., we could make it to the station with nStops-1
nextMaxFuel[k] = maxFuel[k-1] - dist + gas
if nextMaxFuel[k-1] >= dist:
nextMaxFuel[k] = max(nextMaxFuel[k], nextMaxFuel[k-1]-dist) # i.e., don't stop at this station, use prior result
if nextMaxFuel[k] == float('-inf'):
break # we won't be able to get to later stations either
#print('after',nStops,'stops',nextMaxFuel)
if nextMaxFuel[-1] >= 0: return nStops
maxFuel = nextMaxFuel
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
stations = [[0,startFuel]] + sorted(stations)
n = len(stations)
reach = [-float('inf')]*n
reach[0] = startFuel
st = [startFuel]*n
flag = True
cnt = 0
if target <= startFuel:
return 0
while flag:
flag = False
cnt += 1
for i in range(1,len(reach))[::-1]:
p, g = stations[i]
st.pop()
if p <= st[-1] and st[-1] + g > reach[i]:
reach[i] = st[-1] + g
flag = True
if reach[i] >= target:
return cnt
for i in range(1,len(reach)):
st.append(max(st[-1],reach[i]))
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
# dp[i]: (a, b). a-> the longest distance a car can travel with i refuels
# b-> the location(distance) of fuels already used
dp=[[startFuel,[]]]
for i in range(len(stations)):
if dp[-1][0]>=target:
break
#print(\" \")
#print(dp)
usedStations=dp[-1][1]
#print(usedStations)
# reachable stations
usable_stations=[s for s in stations if s[0]<=dp[-1][0] and s[0] not in usedStations]
usable_stations.sort(key=lambda x:x[1])
if len(usable_stations)==0:
break
#print(usable_stations)
dp.append([dp[-1][0]+usable_stations[-1][1], dp[-1][1].copy()])
dp[-1][1].append(usable_stations[-1][0])
return len(dp)-1 if dp[-1][0]>=target else -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
n = len(stations)
dp = [[0] * (n + 1) for _ in range(n + 1)]
for row in dp:
row[0] = startFuel
if startFuel >= target: return 0
for refuels in range(1, n+1):
for stas in range(refuels, n+1):
station = stations[stas-1]
dp[stas][refuels] = dp[stas-1][refuels]
if dp[stas-1][refuels-1] >= station[0]:
dp[stas][refuels] = max(station[1] + dp[stas-1][refuels-1], dp[stas][refuels])
if dp[n][refuels] >= target: return refuels
return -1
# for refue in range(1, n + 1):
# for station in range(1, n + 1):
# dp[station][refue] = dp[station - 1][refue]
# if dp[station - 1][refue - 1] >= stations[station - 1][0]:
# dp[station][refue] = max(dp[station - 1][refue - 1] + stations[station - 1][1], dp[station][refue])
# if dp[n][refue] >= target:
# return refue
# return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
return self.dp(target, startFuel, stations)
def dp(self, target, startFuel, stations):
if startFuel >= target:
return 0
if not stations:
return -1
# A[t][i] = max distance using first i stations and stop t times (t<=i)
# A[t][i] = max(
# A[t][i-1],
# A[t-1][i-1] + stations[i-1][1] if A[t-1][i-1] >= stations[i-1][0]
n = len(stations)
A = [[0] * (n+1) for _ in range(n+1)]
for i in range(n+1):
A[0][i] = startFuel
for t in range(1, n+1):
for i in range(1, n+1):
if t <= i:
A[t][i] = A[t][i-1]
if A[t-1][i-1] >= stations[i-1][0]:
A[t][i] = max(A[t][i], A[t-1][i-1] + stations[i-1][1])
if A[t][-1] >= target:
return t
return -1
def rec1(self, target, startFuel, stations, position, station_idx_start):
if position >= target or startFuel >= (target - position):
#print(target, startFuel, stations, position)
return 0
else:
candidates = []
for idx in range(station_idx_start, len(stations)):
p, f = stations[idx]
d = p - position
valid = d > 0 and startFuel - d >= 0
if valid:
candidates.append(1 + self.rec(
target,
startFuel - d + f,
stations,
p,
station_idx_start + 1))
if startFuel - d < 0:
break
if not candidates:
return float('inf')
else:
return min(candidates)
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
n = len(stations)
dp = [[0] * (n + 1) for _ in range(n + 1)]
for row in dp:
row[0] = startFuel
if startFuel >= target: return 0
for refuels in range(1, n+1):
for stas in range(1, n+1):
station = stations[stas-1]
dp[stas][refuels] = dp[stas-1][refuels]
if dp[stas-1][refuels-1] >= station[0]:
dp[stas][refuels] = max(station[1] + dp[stas-1][refuels-1], dp[stas][refuels])
if dp[n][refuels] >= target: return refuels
return -1
# for refue in range(1, n + 1):
# for station in range(1, n + 1):
# dp[station][refue] = dp[station - 1][refue]
# if dp[station - 1][refue - 1] >= stations[station - 1][0]:
# dp[station][refue] = max(dp[station - 1][refue - 1] + stations[station - 1][1], dp[station][refue])
# if dp[n][refue] >= target:
# return refue
# return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
# f[i,j], the maximum full one can have, using j stations, stop at station i,
# f[i,j] = f[i], j implied by iteration
if target<=startFuel:
return 0
stations=[[0, startFuel]]+stations
print(stations)
N=len(stations)
f = [startFuel-stations[i][0] for i in range(N)]
f[0]=startFuel
print(f)
for j in range(N):
g = [-1]*(N)
g[0]=f[0]
for i in range(N-1,0,-1):
if f[i-1]-(stations[i][0]-stations[i-1][0])>=0:
g[i]=f[i-1]+stations[i][1]-(stations[i][0]-stations[i-1][0])
for i in range(1,N):
g[i]=max(g[i-1]-(stations[i][0]-stations[i-1][0]), g[i])
f = g
if f[-1]>=(target-stations[-1][0]):
return j+1
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, t: int, f: int, st: List[List[int]]) -> int:
if f >= t: return 0
if st == []: return -1
if f < st[0][0]: return -1
li,li1 = [],[]
for i,j in st:
li.append(i)
li1.append(j)
count = 0
while f < t:
s,tur = 0,[]
for i in li:
if f >= i:
s = li.index(i)
tur.append(True)
else: tur.append(False)
print(tur)
if all(i == False for i in tur): return -1
f += max(li1[0:s+1])
li.pop(li1.index(max(li1[0:s+1])))
li1.remove(max(li1[0:s+1]))
count +=1
return count
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if target<=startFuel:
return 0
dp=[[0 for _ in range(len(stations)+1)] for _ in range(len(stations)+1)]
for i in range(len(stations)+1):
dp[i][0]=startFuel
for i in range(1, len(stations)+1):
for j in range(1, len(stations)+1):
dp[j][i]=dp[j-1][i]
if dp[j-1][i-1]>=stations[j-1][0]:
dp[j][i]=max(dp[j][i], dp[j-1][i-1]+stations[j-1][1])
if dp[j][i]>=target:
return i
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
from functools import lru_cache
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
@lru_cache(None)
def farthest_of_first_n_with_stops(n, stops):
if n == 0 or stops == 0:
return startFuel
dont_refuel_now = farthest_of_first_n_with_stops(n - 1, stops)
refuel_now = farthest_of_first_n_with_stops(n - 1, stops - 1)
x, fuel = stations[n - 1]
if refuel_now < x: # can't reach stations[n - 1]
return dont_refuel_now
else:
return max(dont_refuel_now, fuel + refuel_now)
for stops in range(len(stations) + 1):
# print(farthest_of_first_n_with_stops(len(stations), stops))
if farthest_of_first_n_with_stops(len(stations), stops) >= target:
return stops
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
@lru_cache(maxsize=None)
def solve(s: int, stops: int) -> int:
if stops == 0 or s < 0:
return startFuel
return max(solve(s - 1, stops), (sub + stations[s][1]) if (sub := solve(s - 1, stops - 1)) >= stations[s][0] else 0)
for i in range(len(stations) + 1):
if solve(len(stations) - 1, i) >= target:
return i
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target:
return 0
if not stations:
return -1
import heapq
queue = [-f for i,f in stations if i <= startFuel]
heapq.heapify(queue)
fuel = startFuel
start = max([i for i in range(len(stations)) if stations[i][0] <= startFuel] + [-1]) + 1
result = 0
while queue and fuel < target:
fuel -= heapq.heappop(queue)
result += 1
while start < len(stations) and fuel >= stations[start][0]:
heapq.heappush(queue, -stations[start][1])
start += 1
return result if fuel >= target else -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if target==startFuel:
return 0
stations=[startFuel]+stations
dp=[0]*len(stations)
dp[0]=(startFuel)
for i in range(1, len(stations)):
j=i-1
while j>=0:
totalFuel=dp[j]+stations[i][1]
if dp[j] >=stations[i][0] and totalFuel>=dp[j+1]:
dp[j+1]=(totalFuel)
j-=1
# print(dp)
for i,fuel in enumerate(dp):
if fuel>=target:return i
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if target <= startFuel:
return 0
if not stations:
return -1
dp = [startFuel]
stops = 0
lastd = 0
for d, fuel in stations:
for i in range(stops, len(dp)):
dp[i] -= d - lastd
if dp[i] < 0:
stops = i + 1
if stops == len(dp):
return -1
dp.append(dp[-1] + fuel)
for i in range(len(dp) - 2, stops, -1):
dp[i] = max(dp[i], dp[i - 1] + fuel)
if dp[stops] >= target - d:
return stops
lastd = d
while stops < len(dp):
if dp[stops] >= target - lastd:
return stops
stops += 1
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
if startFuel >= target: return 0
heap = []
for d, g in stations:
heapq.heappush(heap, (-g, d))
dist = startFuel
stop = 0
dist = startFuel
tmp = []
while heap:
g, d = heapq.heappop(heap)
if d <= dist:
dist += -g
if dist >= target:
return stop + 1
for el in tmp:
heapq.heappush(heap, el)
tmp = []
stop += 1
else:
tmp.append((g, d))
return -1
|
A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
|
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
stations = [[0,0]] + stations
heap = [(0, 0, -startFuel)]
seen = {}
while heap:
stop, pos, fuel = heappop(heap)
pos = -pos
fuel = -fuel
if pos in seen and seen[pos] >= fuel:
continue
seen[pos] = fuel
if stations[pos][0] + fuel >= target:
return stop
if pos+1 < len(stations) and fuel >= stations[pos+1][0] - stations[pos][0]:
new_fuel = fuel - (stations[pos+1][0] - stations[pos][0])
heappush(heap, (stop+1, -(pos+1), -(new_fuel + stations[pos+1][1])))
heappush(heap, (stop, -(pos+1), -new_fuel))
return -1
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n < 2: return 0
sells = [0] * n
buys = [0] * n
buys[0] = -prices[0]
for i in range(1, n):
sells[i] = max(sells[i-1], buys[i-1] + prices[i])
buys[i] = max(buys[i-1], (sells[i-2] if i > 1 else 0) - prices[i])
return sells[n-1]
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
sell = hold = 0
buy = -prices[0]
for i in range(1, len(prices)):
sell, hold, buy = max(buy + prices[i], 0), max(hold, sell), max(hold-prices[i], buy)
return max(sell, hold)
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices is None or len(prices) == 0:
return 0
# 0 for buy 1 for sell 2 for break
dp = [[-9999999]*len(prices) for _ in range(3)]
dp[0][0], dp[1][0], dp[2][0] = -prices[0], 0, 0
for i in range(1, len(prices)):
dp[0][i] = max(dp[0][i-1], dp[2][i-1] - prices[i])
dp[1][i] = max(dp[0][i-1] + prices[i], dp[1][i-1])
dp[2][i] = max(dp[2][i-1], dp[0][i-1], dp[1][i-1])
return max(dp[1][-1], dp[2][-1])
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if not n:
return 0
buys = [None] * n
sells = [None] * n
sells[0], buys[0] = 0, -prices[0]
for x in range(1, n):
delta = prices[x] - prices[x - 1]
sells[x] = max(buys[x - 1] + prices[x], sells[x - 1] + delta)
buys[x] = max(buys[x - 1] - delta, sells[x - 2] - prices[x] if x > 1 else -9999)
return max(sells)
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n < 2:
return 0
buy, sell = [0]*n, [0]*n
buy[0], buy[1] = -prices[0], -min(prices[0:2])
sell[1] = max(0, buy[0] + prices[1])
for i in range(2, n):
sell[i] = max(sell[i-1], buy[i-1] + prices[i])
buy[i] = max(buy[i-1], sell[i-2] - prices[i])
return sell[-1]
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) == 1:
return 0
valid_status = [0, [prices[0], -prices[0]], 0]
for t in range(1, len(prices)):
valid_status[1][0] = prices[t]
# cool down status
cool_down_temp = sum(valid_status[1])
if valid_status[0] > sum(valid_status[1]):
valid_status[1] = [prices[t], valid_status[0] - prices[t]]
if valid_status[2] > valid_status[0]:
valid_status[0] = valid_status[2]
valid_status[2] = cool_down_temp
return max(valid_status[0], valid_status[2])
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
max_buy = [0]*len(prices)
max_sell = [0]*len(prices)
max_rest = [0]*len(prices)
max_buy[0] = -prices[0]
max_sell[0] = 0
max_rest[0] = 0
for i in range(1, len(prices)):
max_buy[i] = max(max_rest[i-1] - prices[i], max_buy[i-1])
max_sell[i] = max(max_buy[i-1] + prices[i], max_sell[i-1])
max_rest[i] = max(max_sell[i-1], max_rest[i-1])
return max(max_buy[-1], max_sell[-1], max_rest[-1])
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
stock = -prices[0]
noStock = 0
noStockSell = 0
for idx in range(len(prices)):
price = prices[idx]
print(noStock, stock, noStockSell)
noStock, stock, noStockSell = [max(price + stock, noStock), max(noStockSell - price, stock), noStock]
return noStock
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
free = 0
have = cool = float("-inf")
for p in prices:
free, have, cool = max(free, cool), max(have, free - p), have + p
return max(free, cool)
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self,prices):
if not prices:
return 0
prices.insert(0,0)
prices.insert(0,0)
buy=[0]*len(prices)
sell=[0]*len(prices)
buy[2]=-prices[2]
for i in range(3,len(prices)):
buy[i]=max(sell[i-2]-prices[i],buy[i-1])
sell[i]=max(buy[i-1]+prices[i],sell[i-1])
return sell[-1]
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self,prices):
if not prices:
return 0
prices.insert(0,0)
prices.insert(0,0)
buy=[0]*len(prices)
sell=[0]*len(prices)
buy[2]=-prices[2]
for i in range(3,len(prices)):
buy[i]=max(sell[i-2]-prices[i],buy[i-1])
sell[i]=max(buy[i-1]+prices[i],sell[i-1])
return sell[-1]
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
return self.max_profit_rec(prices, {}, 0, 0)
def max_profit_rec(self, prices, memo, idx, state):
if idx >= len(prices): return 0
if (idx, state) in memo: return memo[(idx, state)]
memo[(idx, state)] = 0
if state == 0:
# can buy or ignore
memo[(idx, state)] = max(self.max_profit_rec(prices, memo, idx+1, 1) - prices[idx], self.max_profit_rec(prices, memo, idx+1, 0))
elif state == 1:
# can sell or ignore
memo[(idx, state)] = max(self.max_profit_rec(prices, memo, idx+1, 2) + prices[idx], self.max_profit_rec(prices, memo, idx+1, 1))
else:
# cooldown: must ignore
memo[(idx, state)] = self.max_profit_rec(prices, memo, idx+1, 0)
return memo[(idx, state)]
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
if len(prices) < 2:
return 0
prevSell,sell,prevBuy,buy = 0,0,0,-prices[0]
for price in prices:
prevBuy = buy
buy = max(prevBuy,prevSell-price)
prevSell = sell
sell = max(prevSell,prevBuy+price)
return sell
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
free=0
have,cool=float('-inf'),float('-inf')
for p in prices:
free,have,cool=max(free,cool),max(free-p,have),have+p
return max(free,cool)
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
result = 0
left = 0
right = len(height) - 1
while left < right:
if height[left] <= height[right]:
tmp = height[left]
left += 1
while left < right and height[left] <= tmp:
result += tmp - height[left]
left += 1
else:
tmp = height[right]
right -= 1
while left < right and height[right] <= tmp:
result += tmp - height[right]
right -=1
return result
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# if len(height) < 3 :
# return 0
# maxTrap = 0
# stack=[]
# i = 0
# while i < len(height):
# if not stack or height[i] <= height[stack[-1]]:
# stack.append(i)
# i += 1
# else :
# bot = stack.pop()
# trap = 0 if not stack else (min(height[i],height[stack[-1]]) - height[bot] ) * (i-stack[-1]-1)
# maxTrap += trap
# # print(stack)
# return maxTrap
if not height :
return 0
left , right = 0 , len(height)-1
maxLeft,maxRight = height[left],height[right]
maxTrap = 0
while left <= right :
if height[left] <= height[right]:
if height[left] > maxLeft :
maxLeft = height[left]
else :
maxTrap += (maxLeft - height[left])
left += 1
else :
if height[right] > maxRight:
maxRight = height[right]
else :
maxTrap += (maxRight -height[right])
right -= 1
return maxTrap
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxRight = 0
maxLeft = 0
left = 0
right = len(height) - 1
ret = 0
while left < right:
maxRight = max(maxRight, height[right])
maxLeft = max(maxLeft, height[left])
if maxLeft > maxRight:
ret += maxRight - height[right]
right -= 1
else:
ret += maxLeft - height[left]
left += 1
return ret
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# sol1: mono stack
# sol2: heap
l_bounds = []
lb = float('-inf')
for h in height:
lb = max(lb, h)
l_bounds.append(lb)
water = 0
rb = float('-inf')
for lb, h in zip(reversed(l_bounds), reversed(height)):
rb = max(rb, h)
water += min(lb, rb) - h
return water
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
ans = 0
max_left, max_right = [0]*len(height), [0]*len(height)
for i in range(1,len(height)):
max_left[i] = max(max_left[i-1], height[i-1])
for i in range(len(height)-2,-1,-1):
max_right[i] = max(max_right[i+1], height[i+1])
# 0 added to take care of negative case i.e current step is greater than both max_left and max_right for that step
for i in range(1,len(height)-1):
ans += max(min(max_left[i], max_right[i]) - height[i], 0)
return ans
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, barHeights):
if barHeights == []:
return 0
numberOfBars = len(barHeights)
leftMaxima = [0 for counter in range(numberOfBars)]
rightMaxima = [0 for counter in range(numberOfBars)]
leftMaxima[0] = barHeights[0]
for counter in range(1, numberOfBars):
leftMaxima[counter] = max(leftMaxima[counter-1], barHeights[counter])
rightMaxima[numberOfBars-1] = barHeights[numberOfBars-1]
for counter in range(numberOfBars-2, -1, -1):
rightMaxima[counter] = max(rightMaxima[counter+1], barHeights[counter])
waterTrapped = 0
for counter in range(0, numberOfBars):
waterTrapped += (min(leftMaxima[counter], rightMaxima[counter]) - barHeights[counter])
return waterTrapped
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
'''Complexity O(n)'''
def trap(self, height):
n = len(height)
l, r, water, minHeight = 0, n - 1, 0, 0
while l < r:
while l < r and height[l] <= minHeight:
water += minHeight - height[l]
l += 1
while r > l and height[r] <= minHeight:
water += minHeight - height[r]
r -= 1
minHeight = min(height[l], height[r])
return water
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left, right = 0, len(height) - 1
result = 0
while left < right:
mh = min(height[left], height[right])
if height[left]< height[right]:
left = left + 1
while height[left] <= mh and left < right:
result = result + mh - height[left]
left = left + 1
else:
right = right - 1
while height[right] <= mh and left < right:
result = result + mh - height[right]
right = right - 1
return result
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
ans = 0
max_left, max_right = [0]*len(height), [0]*len(height)
for i in range(1,len(height)):
max_left[i] = max(max_left[i-1], height[i-1])
for i in range(len(height)-2,-1,-1):
max_right[i] = max(max_right[i+1], height[i+1])
# 0 added to take care of negative case i.e current step is greater than both max_left and max_right for that step
for i in range(1,len(height)-1):
ans += max(min(max_left[i], max_right[i]) - height[i], 0)
return ans
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
leftmaxes = []
rightmaxes = []
maximum = 0
for i in range(len(height)):
maximum = max(maximum, height[i])
leftmaxes.append(maximum)
maximum = 0
for i in range(len(height)):
maximum = max(maximum, height[len(height) - i - 1])
rightmaxes.append(maximum)
water = 0
print(leftmaxes)
print(rightmaxes)
for i in range(len(height)):
trappable = min(leftmaxes[i], rightmaxes[-i-1])
if(trappable > height[i]):
water += trappable - height[i]
return water
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
length = len(height)
if(length == 0):
return 0
maxLeft = [0] * length
maxRight = [0] * length
result = 0
maxLeft[0] = height[0]
maxRight[length - 1] = height[length - 1]
for i in range(1,length):
maxLeft[i] = max(maxLeft[i - 1], height[i])
for i in reversed(list(range(0, length - 1))):
maxRight[i] = max(maxRight[i + 1], height[i])
for i in range(length):
result += min(maxLeft[i], maxRight[i]) - height[i]
return result
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# find valleys
N = len(height)
valleys = [] # a list of [left, right] (not inclusive) bounds of local minimum
i = 0
while i < N-1:
# first go uphills and then down hills until flat or up hills, this is a potential left bound of a valley
while i < N-1 and height[i] <= height[i+1]: i += 1
while i < N-1 and height[i] > height[i+1]: i += 1 # ensures height[i] <= height[i+1] unless out of bounds
j = i
while j < N-1 and height[j] == height[j+1]: j += 1 # go through the range of the potential bottom of the valley
if j < N-1 and height[j] < height[j+1]: valleys.append([i-1,j+1]) # store a confirmed valley with bottom [i:j+1]
i = j
# fill water into each valley
total_water = 0
further_valleys = [] # list of potential valley to merge as those whose left side is higher after water filll
k = 0
if valleys: # initialize
l = valleys[k][0]
r = valleys[k][1]
old_level = height[l+1]
while k < len(valleys):
# record bottom level
water = 0
while l >= 0 and r < N and height[l] >= height[l+1] and height[r-1] <= height[r]: # both sides rising
# fill water at [l+1:r]
new_level = min(height[l], height[r])
water += (new_level - old_level) * (r - l - 1)
old_level = new_level
# advance to the next level in the valley
if l >= 0 and r < N:
# rise only the lower side
if height[l] == height[r]:
l -= 1
r += 1
elif height[l] < height[r]: l -= 1
else: r += 1
# make sure level rises
while l >= 0 and height[l] == height[l+1]: l -= 1
while r < N and height[r-1] == height[r]: r += 1
total_water += water
# l == -1 or r == N or height[l] < height[l+1] or height[r-1] > height[r]
if l >= 0 and r < N:
if height[l] > height[l+1]: # further rise is possible after the next valley is filled
further_valleys.append([l,r])
elif further_valleys and height[further_valleys[-1][1]-1] == height[l+1]: # merge two valleys
old_level = height[l+1] # water already filled to this level
l = further_valleys[-1][0]
further_valleys.pop()
continue # fill the merged valley before moving on
# fill the next valley
k += 1
if k < len(valleys):
l = valleys[k][0]
r = valleys[k][1]
old_level = height[l+1]
return total_water
|
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
|
class Solution:
def get_empty_per_level(self, height, level):
print(("Level: ", level))
block_start = 0
n = len(height)
while block_start < n and height[block_start] < level:
block_start += 1
if block_start == n:
print("No start")
return n
block_end = n - 1
while block_end > block_start and height[block_end] < level:
block_end -= 1
if block_end == block_start:
print("No end")
return n - 1
print("Some value")
return n - (block_end - block_start + 1)
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height or len(height) == 0:
return 0
levels = set(height)
levels = list(levels)
if 0 in levels:
levels.remove(0)
levels.sort()
if len(levels) == 0:
return 0
max_level = max(height)
total_count = sum([max_level - item for item in height])
prev_level = levels.pop(0)
missing_water_per_level = self.get_empty_per_level(height, prev_level)
total_count -= prev_level * missing_water_per_level
for level in levels:
missing_water_per_level = self.get_empty_per_level(height, level)
multi_level_count = (level - prev_level) * missing_water_per_level
total_count -= multi_level_count
#print("Level: ", level, " count after: ", total_count, "missing water: ", missing_water_per_level)
prev_level = level
return total_count
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
# DP(a=index of last, b=index of last) = max of:
# DP(a-1, b)
# DP(a-1, i) + nums1[a] * max_or_min(nums2[i+1:b+1])
# same for b
INF = int(1e9)
n, m = len(nums1), len(nums2)
DP = [-INF] * (m + 1)
NDP = [-INF] * (m + 1)
for a in range(n):
for b in range(m):
el = nums1[a] * nums2[b]
diag = DP[b]
NDP[b + 1] = max(el, DP[b + 1], NDP[b], diag, diag + el)
DP, NDP = NDP, DP
return DP[-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
if all(x >= 0 for x in nums1) and all(y <= 0 for y in nums2):
return min(nums1) * max(nums2)
if all(x <= 0 for x in nums1) and all(y >= 0 for y in nums2):
return max(nums1) * min(nums2)
accu_max = [0] * (len(nums2) + 1)
for i in range(len(nums1)):
last_max = [accu_max[j] + nums1[i] * nums2[j] for j in range(len(nums2))]
this_accu_max = [0]
for j in range(len(nums2)):
this_accu_max.append(max(this_accu_max[-1], last_max[j], accu_max[j + 1]))
accu_max = this_accu_max
return accu_max[-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1 = len(nums1)
n2 = len(nums2)
dp = [[0] * (n2+1) for j in range(n1+1)]
for i in range(n1):
for j in range(n2):
dp[i+1][j+1] = max(dp[i][j] + max(0, nums1[i] * nums2[j]), dp[i][j+1], dp[i+1][j])
# print(dp)
if dp[-1][-1] != 0:
return dp[-1][-1]
nums1.sort()
nums2.sort()
a = nums1[0] if nums1[0] > 0 else nums1[-1]
b = nums2[0] if nums2[0] > 0 else nums2[-1]
return a * b
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
import numpy as np
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
# DP(a=index of last, b=index of last) = max of:
# DP(a-1, b)
# DP(a-1, i) + nums1[a] * max_or_min(nums2[i+1:b+1])
# same for b
INF = int(1e9)
n, m = len(nums1), len(nums2)
DP = np.ones((n, m), dtype=int) * -INF
DP[0, 0] = nums1[0] * nums2[0]
for a in range(n):
for b in range(m):
el = nums1[a] * nums2[b]
curr = el
if a > 0:
curr = max(curr, DP[a - 1, b])
if b > 0:
curr = max(curr, DP[a, b - 1])
if a > 0 and b > 0:
prev = DP[a - 1, b - 1]
curr = max(curr, prev, prev + el)
DP[a, b] = curr
return DP[-1, -1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
from functools import lru_cache
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
m = len(nums2)
@lru_cache(None)
def dp(i, j, selected):
if i == n or j == m:
return 0 if selected else -1000000000
a = nums1[i] * nums2[j] + dp(i + 1, j + 1, True)
b = dp(i, j + 1, selected)
c = dp(i + 1, j, selected)
return max(a, b, c)
return dp(0, 0, False)
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
def dp(nums1, nums2, i, j, m, n, dic):
if(i+1>=m):
maximum = None
for p in range(j,n):
if(maximum == None):
maximum = nums1[i] * nums2[p]
else:
maximum = max(maximum,nums1[i] * nums2[p])
return maximum
elif(j+1 >= n):
maximum = None
for p in range(i,m):
if(maximum == None):
maximum = nums1[p] * nums2[j]
else:
maximum = max(maximum,nums1[p] * nums2[j])
return maximum
if(dic[i][j] != None):
return dic[i][j]
dic[i][j] = max(nums1[i] * nums2[j],nums1[i] * nums2[j] + dp(nums1,nums2,i+1,j+1,m,n,dic), dp(nums1,nums2,i,j+1,m,n,dic), dp(nums1,nums2,i+1,j,m,n,dic), dp(nums1,nums2,i+1,j+1,m,n,dic))
return dic[i][j]
dic = []
m = len(nums1)
n = len(nums2)
for i in range(m):
dic.append([None]*n)
return dp(nums1,nums2,0,0,m,n,dic)
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
@lru_cache(None)
def cal(i, j):
if i >= len(nums1) or j >= len(nums2):
return 0
return max(nums1[i]*nums2[j] + cal(i+1, j+1), cal(i, j+1), cal(i+1, j))
ans = cal(0, 0)
if ans == 0:
return max(min(nums1)*max(nums2), min(nums2)*max(nums1))
else:
return ans
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
import numpy as np
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
M = np.zeros((len(nums1), len(nums2)), dtype=np.int)
M[0][0] = nums1[0]*nums2[0]
for i in range(1, len(nums1)):
M[i][0] = max(M[i-1][0], nums1[i]*nums2[0])
for j in range(1, len(nums2)):
M[0][j] = max(M[0][j-1], nums1[0]*nums2[j])
for i in range(1, len(nums1)):
for j in range(1, len(nums2)):
M[i][j] = max(M[i-1][j-1]+nums1[i]*nums2[j], M[i][j-1], M[i-1][j], nums1[i]*nums2[j])
# print(M)
return M[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
cache = {}
def process(i, j, k):
if not (i, j, k) in cache:
ans = 0
if i == 0 and j == 0:
if k == 0:
ans = nums1[i] * nums2[j]
else:
ans = max(nums1[i] * nums2[j], 0)
elif i == 0:
ans = max(nums1[i] * nums2[j], process(i, j-1, k))
elif j == 0:
ans = max(nums1[i] * nums2[j], process(i-1, j, k))
else:
ans = max(nums1[i] * nums2[j] + process(i-1, j-1, 1), process(i-1, j, k), process(i, j-1, k))
cache[(i, j, k)] = ans
return cache[(i, j, k)]
return process(n1-1, n2-1, 0)
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
mi = -100000000000
dp = [[mi]*(505) for i in range(505)]
def steps(i,j,lis1,lis2):
best = mi
if i<0 or j<0:
return 0
elif dp[i][j]!=mi:
return dp[i][j]
if i==0:
for _ in range(j+1):
best = max(lis1[i]*lis2[_] , best)
dp[i][j]=best
return dp[i][j]
if j==0:
for _ in range(i+1):
best = max(lis1[_]*lis2[j] , best)
dp[i][j]=best
return best
best = max(steps(i-1,j,lis1,lis2) , steps(i,j-1,lis1,lis2) , lis1[i]*lis2[j] + steps(i-1,j-1,lis1,lis2) , lis1[i]*lis2[j])
dp[i][j]=best
return dp[i][j]
class Solution:
def maxDotProduct(self, lis1: List[int], lis2: List[int]) -> int:
n = len(lis1)
m = len(lis2)
for i in range(501):
for j in range(501):
dp[i][j]=mi
steps(n-1,m-1,lis1,lis2)
return dp[n-1][m-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
# m, n = len(nums1), len(nums2)
# dp = [float(\"-inf\") * (n + 1) for _ in range(m + 1) ]
# for i in range(1, m + 1):
# for j in range(1, n + 1):
# dp[i][j] = max(dp[i-1][j], dp[i][j-1], max(0, dp[i-1][j-1]) + nums1[i] * nums2[j])
# return dp[m][n]
m,n = len(nums1),len(nums2)
INF = -100000000
dp = [[INF]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j] = nums1[i-1] * nums2[j-1]
dp[i][j] = max(dp[i][j], dp[i-1][j], dp[i][j-1], dp[i][j]+dp[i-1][j-1])
return dp[m][n]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
def f(nums1, nums2, i, j, D):
if i == 0 or j == 0:
return 0
elif str([i,j]) in D:
return D[str([i,j])]
res = max(nums1[i-1] * nums2[j-1] + f(nums1, nums2, i-1, j-1, D), f(nums1, nums2, i-1, j, D), f(nums1, nums2, i, j-1, D))
D[str([i,j])] = res
return res
D = {}
res = f(nums1, nums2, len(nums1), len(nums2), D)
if res == 0 and (max(nums1) < 0 and min(nums2) > 0):
return max(nums1) * min(nums2)
elif res == 0 and (max(nums2) < 0 and min(nums1) > 0):
return max(nums2) * min(nums1)
return res
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp=[[0]*len(nums2) for _ in nums1]
res=-float('inf')
for i in range(len(nums1)):
for j in range(len(nums2)):
if i==0 or j==0:
if i==0 and j==0:
dp[i][j]=nums1[i]*nums2[j]
elif i==0:
dp[i][j]=max(dp[i][j-1],nums1[i]*nums2[j])
else:
dp[i][j]=max(dp[i-1][j],nums1[i]*nums2[j])
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1],nums1[i]*nums2[j],nums1[i]*nums2[j]+dp[i-1][j-1])
res=max(res,dp[i][-1])
#print(dp)
return res
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
M = [[-100000] * (n2 + 1) for _ in range(n1 + 1)]
for i in range(n1):
for j in range(n2):
M[i+1][j+1] = max(M[i][j]+nums1[i]*nums2[j], M[i][j+1], M[i+1][j], nums1[i]*nums2[j])
return M[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
max_dot_product = [nums1[0]*num for num in nums2]
max_dot_product = list(itertools.accumulate(max_dot_product, max))
for num1 in nums1[1:]:
max_dot_product_next = []
for i, num2 in enumerate(nums2):
curr_max = max_dot_product[i]
if i > 0:
curr_max = max(curr_max, max(num1*num2+max_dot_product[i-1], max_dot_product_next[i-1]))
curr_max = max(curr_max, num1*num2)
max_dot_product_next.append(curr_max)
max_dot_product = max_dot_product_next
#print(num1, max_dot_product)
#print(max_dot_product)
return max(max_dot_product)
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1 = len(nums1)
n2 = len(nums2)
dp = [[0 for _ in range(n2)] for _ in range(n1)]
for i in range(n1):
for j in range(n2):
curr = nums1[i]*nums2[j]
if i==0 and j==0:
dp[i][j] = curr
elif i==0:
dp[i][j] = max(curr, dp[i][j-1])
elif j==0:
dp[i][j] = max(curr, dp[i-1][j])
else:
dp[i][j] = max(curr, curr+dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
return dp[n1-1][n2-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
M = len(nums1)
N = len(nums2)
dp = [[0] * N for _ in range(M)]
dp[0][0] = nums1[0] * nums2[0]
for i in range(1, M):
dp[i][0] = max(dp[i-1][0], nums2[0] * nums1[i])
for i in range(1, N):
dp[0][i] = max(dp[0][i-1], nums1[0] * nums2[i])
for i in range(1, M):
for j in range(1, N):
dp[i][j] = max(dp[i-1][j-1], dp[i-1][j-1] + nums1[i]*nums2[j], dp[i-1][j], dp[i][j-1], nums1[i]*nums2[j])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, a: List[int], b: List[int]) -> int:
nums1 = [0] + a
nums2 = [0] + b
m, n = len(nums1), len(nums2)
dp = [[float('-inf')] * m for _ in range(n)]
for i in range(1, n):
for j in range(1, m):
if nums1[j] * nums2[i] > 0:
dp[i][j] = max(dp[i-1][j-1] + nums1[j] * nums2[i], dp[i][j-1], dp[i-1][j], nums1[j] * nums2[i])
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j], nums1[j] * nums2[i])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1, nums2) -> int:
n, m = len(nums1), len(nums2)
# dp[i][j] max dot product of nums[:i+1][:j+1]
dp = [[0 for _ in range(m)] for _ in range(n)]
dp[0][0] = nums1[0]*nums2[0]
for j in range(1, m):
dp[0][j] = max(dp[0][j-1], nums1[0]*nums2[j])
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], nums1[i]*nums2[0])
for i in range(1, n):
for j in range(1, m):
dp[i][j] = max(nums1[i]*nums2[j],
dp[i-1][j-1] + nums1[i]*nums2[j],
dp[i-1][j],
dp[i][j-1],
dp[i-1][j-1])
return dp[n-1][m-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1: int = len(nums1)
n2: int = len(nums2)
dp: List[List[int]] = [[float('-inf') for _ in range(n2 + 1)] for _ in range(n1 + 1)]
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], max(0, dp[i - 1][j - 1]) + nums1[i - 1] * nums2[j - 1])
return dp[n1][n2]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
# dp(x, y) = max([nums1[x]*nums2[y] + dp(x-1, y-1), dp(x-1, y), dp(x, y-1)])
dp = [[0 for i in range(len(nums2)+1)] for j in range(len(nums1)+1)]
for i in range(len(nums1)):
for j in range(len(nums2)):
dp[i+1][j+1] = max([dp[i][j] + nums1[i]*nums2[j], dp[i+1][j], dp[i][j+1]])
return dp[len(nums1)][len(nums2)] if dp[len(nums1)][len(nums2)] > 0 else max([max(nums1) * max(nums2), min(nums1) * min(nums2), max(nums1) * min(nums2), min(nums1) * max(nums2)])
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0]*(len(nums2)) for _ in range(len(nums1))]
for i in range(len(nums1)):
for j in range(len(nums2)):
if(i == 0 and j == 0):
dp[i][j] = nums1[0]*nums2[0]
continue
prod = nums1[i]*nums2[j]
if(i == 0):
dp[i][j] = max(dp[i][j-1], prod)
continue
if(j == 0):
dp[i][j] = max(dp[i-1][j], prod)
continue
dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]+prod, prod)
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[-float('inf')] * (n + 1) for i in range(m+1)]
res = -float('inf')
for i in range(1, m+1):
for j in range(1, n+1):
dp[i][j] = max(
dp[i-1][j], dp[i][j-1],
dp[i-1][j-1]+nums1[i-1]*nums2[j-1],
nums1[i-1]*nums2[j-1]
)
for row in dp:
for x in row:
res = max(res, x)
return res
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0]*n for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = nums1[i] * nums2[j]
elif i == 0:
dp[i][j] = max(dp[i][j-1], nums1[i] * nums2[j])
elif j == 0:
dp[i][j] = max(dp[i-1][j], nums1[i] * nums2[j])
else:
temp = nums1[i] * nums2[j]
dp[i][j] = max(temp, dp[i-1][j], dp[i][j-1], dp[i-1][j-1] + temp)
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp=[[0 for _ in range(len(nums2))] for _ in range(len(nums1))]
dp[-1][-1]=nums1[-1]*nums2[-1]
for i in range(len(nums1)-2,-1,-1):
dp[i][-1]=max(dp[i+1][-1],nums1[i]*nums2[-1])
for i in range(len(nums2)-2,-1,-1):
dp[-1][i]=max(dp[-1][i+1],nums1[-1]*nums2[i])
for i in range(len(nums1)-2,-1,-1):
for j in range(len(nums2)-2,-1,-1):
dp[i][j]=max(dp[i+1][j+1],dp[i+1][j],dp[i][j+1],dp[i+1][j+1]+(nums1[i]*nums2[j]),nums1[i]*nums2[j])
return dp[0][0]
# def backtrack(arr,ind,curr,sol):
# if curr:
# sol[len(curr)-1].append(curr)
# for i in range(ind,len(arr)):
# backtrack(arr,i+1,curr+[arr[i]],sol)
# subs1=[[] for _ in range(len(nums1))]
# subs2=[[] for _ in range(len(nums2))]
# backtrack(nums1,0,[],subs1)
# backtrack(nums2,0,[],subs2)
# mx=float(\"-inf\")
# for i in range(min(len(nums1),len(nums2))):
# for j in range(len(subs1[i])):
# for k in range(len(subs2[i])):
# ans=0
# for l in range(i+1):
# ans+=subs1[i][j][l]*subs2[i][k][l]
# mx=max(mx,ans)
# return mx
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
N = len(nums1)
M = len(nums2)
if max(nums1)<0 and min(nums2)>0:
return max(nums1) * min(nums2)
if max(nums2)<0 and min(nums1)>0:
return min(nums1) * max(nums2)
dp = [[0 for i in range(M+1)] for j in range(N+1)]
for i in range(N):
for j in range(M) :
dp[i+1][j+1] = max(dp[i][j]+nums1[i]*nums2[j], dp[i][j+1], dp[i+1][j])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[0]*len(nums2) for _ in range(len(nums1))]
dp[0][0] = max(0,nums1[0] * nums2[0])
for i in range(0,len(nums1)):
for j in range(0,len(nums2)):
if i>0 and j>0:
dp[i][j] = max(dp[i-1][j-1], dp[i][j-1], dp[i-1][j], dp[i-1][j-1] + nums1[i] * nums2[j])
else:
if j>0 and i==0:
dp[i][j] = max(dp[i][j-1], nums1[i] * nums2[j])
if i>0 and j==0:
dp[i][j] = max(dp[i-1][j], nums1[i] * nums2[j])
#print(i,j,dp[i][j])
# print(dp)
# print(max(dp))
ans = max([max(x) for x in dp])
if ans>0:
return ans
else:
best = -9999999
for k in nums1:
for l in nums2:
best = max(best, k*l)
return best
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1=len(nums1)
n2=len(nums2)
dp=[[[0,0] for i in range(n2)] for j in range(n1)]
for i in range(n1):
for j in range(n2):
if i==0:
if j==0:
dp[i][j]=nums1[i]*nums2[j]
else:
dp[i][j]=max(dp[i][j-1],nums1[i]*nums2[j])
elif j==0:
dp[i][j]=max(dp[i-1][j],nums1[i]*nums2[j])
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1],nums1[i]*nums2[j]+dp[i-1][j-1],dp[i-1][j-1],nums1[i]*nums2[j])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
N = len(nums1)
M = len(nums2)
dp = [[0] * M for _ in range(N)]
dp[0][0] = nums1[0] * nums2[0]
res = dp[0][0]
big = nums1[0] >= 0
acc = nums2[0]
for i, x in enumerate(nums2[1:]):
if big and x > acc:
acc = x
elif not big and x < acc:
acc = x
dp[0][i+1] = acc * nums1[0]
res = max(res, dp[0][i+1])
big = nums2[0] >= 0
acc = nums1[0]
for i, x in enumerate(nums1[1:]):
if big and x > acc:
acc = x
elif not big and x < acc:
acc = x
dp[i+1][0] = acc * nums2[0]
res = max(res, dp[i+1][0])
for i in range(1, N):
for j in range(1, M):
dp[i][j] = max(dp[i-1][j], dp[i][j-1], nums1[i] * nums2[j] + max(0, dp[i-1][j-1]))
res = max(res, dp[i][j])
return res
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
dp = [[-sys.maxsize-1 for i in range(len(nums2)+1)] for j in range(len(nums1)+1)]
for i in range(1,len(nums1)+1):
for j in range(1,len(nums2)+1):
t = nums1[i-1]*nums2[j-1]
dp[i][j] = max({dp[i-1][j-1]+t,t,dp[i-1][j], dp[i][j-1]})
# print(dp)
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
mem = [[float('-inf')] * (n2+1) for _ in range(n1+1)]
mem[0][0] = 0
for i in range(1, n1+1):
for j in range(1, n2+1):
mem[i][j] = max(mem[i][j], max(nums1[i-1]*nums2[j-1] + max(0, mem[i-1][j-1]), mem[i][j-1], mem[i-1][j]))
# print(mem)
return mem[n1][n2]
# mem = [[[[float('-inf')] * n2 for j in range(n2)] for i1 in range(n1)] for i2 in range(n1)]
@lru_cache
def dp(i1, j1, i2, j2):
if i1 > j1 or i2 > j2:
return 0
if i1 == j1 and i2 == j2:
return nums1[i1]*nums2[i2]
if mem[i1][j1][i2][j2] != float('-inf'):
return mem[i1][j1][i2][j2]
ans = float('-inf')
for k1 in range(i1, j1+1):
for k2 in range(i2, j2+1):
ans = max(ans, max(0, nums1[k1] * nums2[k2]) + dp(i1, k1-1, i2, k2-1) + dp(k1+1, j1, k2+1, j2))
mem[i1][j1][i2][j2] = ans
return ans
return dp(0, n1-1, 0, n2-1)
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, A, B):
n, m = len(A), len(B)
dp = [[0] * (m) for i in range(n)]
for i in range(n):
for j in range(m):
dp[i][j] = A[i] * B[j]
if i and j: dp[i][j] += max(dp[i - 1][j - 1], 0)
if i: dp[i][j] = max(dp[i][j], dp[i - 1][j])
if j: dp[i][j] = max(dp[i][j], dp[i][j - 1])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, A, B):
n, m = len(A), len(B)
dp = [[0] * (m) for i in range(n)]
for i in range(n):
for j in range(m):
dp[i][j] = A[i] * B[j]
if i and j:
dp[i][j] += max(dp[i - 1][j - 1], 0)
if i:
dp[i][j] = max(dp[i][j], dp[i - 1][j])
if j:
dp[i][j] = max(dp[i][j], dp[i][j - 1])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
m = len(nums2)
dp = [[0] * m for i in range(n)]
dp[0][0] = nums1[0] * nums2[0]
for j in range(1, m):
dp[0][j] = max(dp[0][j - 1], nums1[0] * nums2[j])
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], nums1[i] * nums2[0])
for i in range(1, n):
for j in range(1, m):
prod = nums1[i] * nums2[j]
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + (prod if prod > 0 else 0), prod)
# print(dp)
return dp[n - 1][m - 1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, A: List[int], B: List[int]) -> int:
n, m = len(A), len(B)
dp = [[0] * (m) for i in range(n)]
for i in range(n):
for j in range(m):
dp[i][j] = A[i] * B[j]
if i and j: dp[i][j] += max(dp[i - 1][j - 1], 0)
if i: dp[i][j] = max(dp[i][j], dp[i - 1][j])
if j: dp[i][j] = max(dp[i][j], dp[i][j - 1])
return dp[-1][-1]
|
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
|
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n1, n2 = len(nums1), len(nums2)
d = [[0] * (n2+1) for _ in range(n1+1)]
inf = -float('inf')
for i in range(n1):
for j in range(n2):
d[i][j] = max(d[i-1][j] if i else inf,d[i][j-1] if j else inf, nums1[i] * nums2[j] + (d[i-1][j-1] if d[i-1][j-1] > 0 else 0))
return d[n1-1][n2-1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.