Input: nums =[3,2,4,4,1], costs =[3,7,6,4,2]Output: 8Explanation: You start at index 0.- Jump to index 2with a cost of costs[2]=6.- Jump to index 4with a cost of costs[4]=2.The total cost is8. It can be proven that 8is the minimum cost needed.Two other possible paths are from index 0->1->4 and index 0->2->3->4.These have a total cost of 9 and 12, respectively.
Example 2:
1
2
3
4
5
6
Input: nums =[0,1,2], costs =[1,1,1]Output: 2Explanation: Start at index 0.- Jump to index 1with a cost of costs[1]=1.- Jump to index 2with a cost of costs[2]=1.The total cost is2. Note that you cannot jump directly from index 0 to index 2 because nums[0]<= nums[1].
We need to find the minimum cost to reach the last index, where jumps are only allowed to the next greater or next smaller element, skipping all elements in between. This is similar to building a graph where each node connects to its next greater and next smaller nodes, and then finding the shortest path using Dijkstra’s algorithm.
import java.util.*
classSolution {
funminCost(nums: IntArray, costs: IntArray): Int {
val n = nums.size
val nxtG = IntArray(n) { -1 }
val nxtS = IntArray(n) { -1 }
val st = ArrayDeque<Int>()
for (i in n-1 downTo 0) {
while (st.isNotEmpty() && nums[st.last()] <= nums[i]) st.removeLast()
if (st.isNotEmpty()) nxtG[i] = st.last()
st.addLast(i)
}
st.clear()
for (i in n-1 downTo 0) {
while (st.isNotEmpty() && nums[st.last()] >= nums[i]) st.removeLast()
if (st.isNotEmpty()) nxtS[i] = st.last()
st.addLast(i)
}
val dist = LongArray(n) { 1e18.toLong() }
dist[0] = costs[0].toLong()
val pq = PriorityQueue(compareBy<Pair<Long, Int>> { it.first })
pq.add(dist[0] to 0)
while (pq.isNotEmpty()) {
val(d, u) = pq.poll()
if (d > dist[u]) continuefor (v in listOf(nxtG[u], nxtS[u])) {
if (v != -1&& dist[v] > d + costs[v]) {
dist[v] = d + costs[v]
pq.add(dist[v] to v)
}
}
}
returnif (dist[n-1] ==1e18.toLong()) -1else dist[n-1].toInt()
}
}
defmin_cost(nums: list[int], costs: list[int]) -> int:
n = len(nums)
nxt_g = [-1]*n
nxt_s = [-1]*n
st = []
for i in range(n-1, -1, -1):
while st and nums[st[-1]] <= nums[i]: st.pop()
if st: nxt_g[i] = st[-1]
st.append(i)
st.clear()
for i in range(n-1, -1, -1):
while st and nums[st[-1]] >= nums[i]: st.pop()
if st: nxt_s[i] = st[-1]
st.append(i)
import heapq
dist = [float('inf')]*n
dist[0] = costs[0]
pq = [(dist[0], 0)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: continuefor v in (nxt_g[u], nxt_s[u]):
if v !=-1and dist[v] > d + costs[v]:
dist[v] = d + costs[v]
heapq.heappush(pq, (dist[v], v))
return-1if dist[n-1] == float('inf') else dist[n-1]