Skip to content

Commit fe531e6

Browse files
committed
Time: 46 ms (80.00%), Space: 44.3 MB (56.92%) - LeetHub
1 parent 6d28a30 commit fe531e6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
Long[][] dp;
3+
public long minimumTotalDistance(List<Integer> robot, int[][] factory) {
4+
Collections.sort(robot); // sorting robot based on position
5+
Arrays.sort(factory,(a,b)->(a[0]-b[0])); // sorting factory based on position
6+
dp = new Long[robot.size()+1][factory.length+1];
7+
return solve(robot,factory,0,0);
8+
}
9+
10+
public long solve(List<Integer> list,int[][] arr,int i,int j){
11+
12+
if(i>=list.size()) return 0L; // if all robot are repaired then there is no robot left to repair so return 0.
13+
if(j>=arr.length) return Long.MAX_VALUE; // here we check if there is no factory left for rapair robot but we have some robot to repair because we didnt pass on first condition.
14+
15+
if(dp[i][j]!=null) return dp[i][j]; // checking memo for already calculated result.
16+
17+
long x = 0;
18+
long res = solve(list,arr,i,j+1); // option 1 - no robot will repair on jth factory
19+
20+
// here we check that ... from i to k will repair on jth factory and other will check with recurstion....
21+
// for k, we will check all possible index from i+1 to array.length
22+
for(int k = i;k<list.size() && k-i+1<=arr[j][1];k++){
23+
x += Math.abs(list.get(k)-arr[j][0]);
24+
long p = solve(list,arr,k+1,j+1);
25+
26+
//p!=maxValue because of maxValue means there is no possible way to repair all robot with that
27+
if(p!=Long.MAX_VALUE){
28+
res = Math.min(res,x+p);
29+
}
30+
}
31+
32+
return dp[i][j] = res;
33+
}
34+
35+
}

0 commit comments

Comments
 (0)