Input: l =10, n =4, k =1, position =[0,3,8,10], time =[5,8,3,6]Output: 62Explanation:
* Merge the signs at indices 1 and 2. Remove the sign at index 1, and change the time at index 2 to `8 + 3 = 11`.* After the merge:*`position` array:`[0, 8, 10]`*`time` array:`[5, 11, 6]`** Segment | Distance (km)| Time per km(min)| Segment Travel Time(min)---|---|---|---0->8|8|5|8×5=408->10|2|11|2×11=22* Total Travel Time:`40 + 22 = 62`, which is the minimum possible time after exactly 1 merge.
Input: l =5, n =5, k =1, position =[0,1,2,3,5], time =[8,3,9,3,3]Output: 34Explanation:
* Merge the signs at indices 1 and 2. Remove the sign at index 1, and change the time at index 2 to `3 + 9 = 12`.* After the merge:*`position` array:`[0, 2, 3, 5]`*`time` array:`[8, 12, 3, 3]`** Segment | Distance (km)| Time per km(min)| Segment Travel Time(min)---|---|---|---0->2|2|8|2×8=162->3|1|12|1×12=123->5|2|3|2×3=6* Total Travel Time:`16 + 12 + 6 = 34`**,** which is the minimum possible time after exactly 1 merge.
To minimize the total travel time after exactly k merges, we need to optimally merge adjacent segments. This is similar to the classical “merge stones” or “matrix chain multiplication” problem, where merging costs are based on segment lengths and times. Dynamic programming with prefix sums helps efficiently compute the minimum cost for all possible merges.
classSolution {
publicintminTravelTime(int l, int n, int k, int[] position, int[] time) {
int[] length =newint[n];
for (int i = 0; i < n - 1; i++) length[i]= position[i + 1]- position[i];
int[][] dp =newint[n][n];
for (int i = 0; i < n; i++) Arrays.fill(dp[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++) dp[i][i]= length[i]* time[i];
for (int merge = 1; merge <= k; merge++) {
for (int i = 0; i + merge < n; i++) {
int j = i + merge;
for (int m = i; m < j; m++) {
dp[i][j]= Math.min(dp[i][j], dp[i][m]+ dp[m + 1][j]);
}
}
}
return dp[0][n - 1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminTravelTime(l: Int, n: Int, k: Int, position: IntArray, time: IntArray): Int {
val length = IntArray(n)
for (i in0 until n - 1) length[i] = position[i + 1] - position[i]
val dp = Array(n) { IntArray(n) { Int.MAX_VALUE } }
for (i in0 until n) dp[i][i] = length[i] * time[i]
for (merge in1..k) {
for (i in0 until n - merge) {
val j = i + merge
for (m in i until j) {
dp[i][j] = minOf(dp[i][j], dp[i][m] + dp[m + 1][j])
}
}
}
return dp[0][n - 1]
}
}
1
2
3
4
5
6
7
8
9
10
11
defmin_travel_time(l: int, n: int, k: int, position: list[int], time: list[int]) -> int:
length = [position[i+1] - position[i] for i in range(n-1)] + [0]
dp = [[float('inf')] * n for _ in range(n)]
for i in range(n):
dp[i][i] = length[i] * time[i]
for merge in range(1, k+1):
for i in range(n - merge):
j = i + merge
for m in range(i, j):
dp[i][j] = min(dp[i][j], dp[i][m] + dp[m+1][j])
return dp[0][n-1]