Bird
Raised Fist0

Given the following code and input, what is the returned total cost?

easy🧾 Code Trace Q3 of Q15
Greedy Algorithms - Two City Scheduling
Given the following code and input, what is the returned total cost?
A120
B110
C150
D160
Step-by-Step Solution
Solution:
  1. Step 1: Sort costs by difference (costA - costB)

    Sorted order: [10,20], [30,20], [400,50], [30,200]
  2. Step 2: Assign first n=2 to city A, rest to city B and sum costs

    City A: 10 + 30 = 40; City B: 50 + 20 = 70; Total = 110
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct sorting and assignment yields 110 [OK]
Quick Trick: Sort by cost difference, assign first half to city A [OK]
Common Mistakes:
MISTAKES
  • Not sorting by difference
  • Assigning wrong half to city A
  • Off-by-one in loop
Trap Explanation:
PITFALL
  • Candidates often forget to sort or misassign halves causing wrong totals.
Interviewer Note:
CONTEXT
  • Tests ability to trace greedy code on canonical input
Master "Two City Scheduling" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes