LeetCode 1066: Campus Bikes II Solution
Master LeetCode problem 1066 (Campus Bikes II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1066. Campus Bikes II
Problem Explanation
Explanation:
- Algorithmic Idea:
- This problem can be solved using dynamic programming with bit manipulation. We can iterate through all possible combinations of assigning bikes to workers and keep track of the minimum distance.
- Step-by-Step Iterations:
- Initialize a dp array of size
2^m(where m is the number of bikes) with all values set to infinity except for the first value which is 0. - Iterate over all workers and bikes pairs and calculate the Manhattan distance between them.
- For each worker, update the dp values based on the distance and the bikes assigned using bit manipulation.
- Finally, the minimum value in the dp array will be the answer.
- Initialize a dp array of size
- Time Complexity: O(w * 2^m) where w is the number of workers and m is the number of bikes.
- Space Complexity: O(2^m) for the dp array.
:
Solution Code
class Solution {
public int assignBikes(int[][] workers, int[][] bikes) {
int w = workers.length, b = bikes.length;
int[][] dp = new int[w][1 << b];
for (int[] arr : dp) {
Arrays.fill(arr, Integer.MAX_VALUE);
}
dp[0][0] = 0;
for (int i = 1; i < w; i++) {
for (int j = 0; j < (1 << b); j++) {
for (int k = 0; k < b; k++) {
if ((j & (1 << k)) == 0) {
dp[i][j | (1 << k)] = Math.min(dp[i][j | (1 << k)], dp[i - 1][j] + dist(workers[i], bikes[k]));
}
}
}
}
int res = Integer.MAX_VALUE;
for (int val : dp[w - 1]) {
res = Math.min(res, val);
}
return res;
}
private int dist(int[] p1, int[] p2) {
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1066 (Campus Bikes II)?
This page provides optimized solutions for LeetCode problem 1066 (Campus Bikes II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1066 (Campus Bikes II)?
The time complexity for LeetCode 1066 (Campus Bikes II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1066 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1066 in Java, C++, or Python.