Hint: Binary search distances, check feasibility with can_place_cows [OK]
Common Mistakes:
Not sorting stalls before binary search
Incorrect binary search boundaries
Miscounting cows placed in can_place_cows
4. Identify the bug in the following Rust function used in the Aggressive Cows problem and select the correct fix:
fn can_place_cows(stalls: &Vec<i32>, cows: i32, dist: i32) -> bool {
let mut count = 0;
let mut last_pos = stalls[0];
for &pos in stalls.iter() {
if pos - last_pos >= dist {
count += 1;
last_pos = pos;
if count == cows {
return true;
}
}
}
false
}
medium
A. Initialize count to cows instead of 0
B. Both A and B
C. Start loop from stalls.iter().skip(1) instead of stalls.iter()
D. No bug, function is correct
Solution
Step 1: Analyze initial count and loop start
Count should start at 1 because first cow is placed at stalls[0]. Loop should skip first stall to avoid counting it twice.
Step 2: Fix both initialization and loop
Set count = 1 and loop with stalls.iter().skip(1) to correctly count cows placed.
Final Answer:
Both A and B -> Option B
Quick Check:
Count=1 and skip first stall in loop [OK]
Hint: Start count at 1 and skip first stall in loop [OK]
Common Mistakes:
Starting count at 0 causes off-by-one error
Looping from first stall counts first cow twice
Returning false incorrectly due to wrong count
5. You have stalls at positions [2, 5, 11, 15, 17, 20] and want to place 4 cows. Using the Aggressive Cows approach, what is the maximum minimum distance you can achieve between any two cows?