I am trying to solve LeetCode problem 1601. Maximum Number of Achievable Transfer Requests :
We have
n
buildings numbered from0
ton - 1
. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.You are given an array requests where
requests[i]
=[fromᵢ, toᵢ]
represents an employee's request to transfer from buildingfromᵢ
to buildingtoᵢ
.All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if
n = 3
and two employees are leaving building0
, one is leaving building1
, and one is leaving building2
, there should be two employees moving to building0
, one employee moving to building1
, and one employee moving to building2
.Return the maximum number of achievable requests.
Below is my attempt:
class Solution {
public int maximumRequests(int n, int[][] requests) {
int[] out= new int[n]; // count outgoing for each building
int[] in= new int[n]; // count incoming for each building
for(int i=0;i<requests.length;i++){
int x=requests[i][0];
int y=requests[i][1];
out[x]++;
in[y]++;
}
int ans=0;
for(int i=0;i<n;i++){
// Achievable transfer happens only when net is ZERO
// so min of in & out can be achieved
ans+=Math.min(in[i],out[i]);
}
return ans;
}
}
Why doesn't the above code work? On further analysis I found that I don't even understand the below example Input/output:
Input:
3
[[2,2],[2,1],[1,0]]
Expected Output:
1
Both requests [2,2],[2,1] can be accepted only if 1 employee leaves building# 1, which is possible as there's a request [1,0]. But for [1,0] to be possible someone should leave building# 0, which is not happening. According to the problem statement initially all buildings are full, so how come one employee goes out from 1 to 0 without someone coming out from 0?
I found someone's backtracking solution, but why is backtracking needed? Why doesn't the above solution work and how does the above example input/output work?