class Solution { fun timeTaken(arrival: IntArray, state: IntArray): IntArray { val n = arrival.size val answer = IntArray(n) { 0 } var currentTime = 0 var previousState: Int? = null var i = 0 while (i < n) { val currentArrival = arrival[i] currentTime = maxOf(currentTime, currentArrival) var j = i // Count how many people arrived at the same time while (j < n && arrival[j] == currentArrival) { j++ } // Separate those who want to enter and exit val entering = mutableListOf<Int>() val exiting = mutableListOf<Int>() for (k in i until j) { if (state[k] == 0) entering.add(k) else exiting.add(k) } // Determine the order based on previous state and current needs if (previousState == null || previousState == 1) { // Prioritize exiting if the door was previously used for exiting or not used for (index in exiting) { answer[index] = currentTime++ } for (index in entering) { answer[index] = currentTime++ } } else { // Prioritize entering if the door was previously used for entering for (index in entering) { answer[index] = currentTime++ } for (index in exiting) { answer[index] = currentTime++ } } // Update previous state for the next iteration previousState = if (exiting.isNotEmpty()) 1 else 0 i = j // Move to the next set of arrivals } return answer } }class Solution { fun timeTaken(arrival: IntArray, state: IntArray): IntArray { val n = arrival.size val answer = IntArray(n) { 0 } var currentTime = 0 var previousState: Int? = null var i = 0 while (i < n) { val currentArrival = arrival[i] currentTime = maxOf(currentTime, currentArrival) var j = i // Count how many people arrived at the same time while (j < n && arrival[j] == currentArrival) { j++ } // Separate those who want to enter and exit val entering = mutableListOf<Int>() val exiting = mutableListOf<Int>() for (k in i until j) { if (state[k] == 0) entering.add(k) else exiting.add(k) } // Determine the order based on previous state and current needs if (previousState == null || previousState == 1) { // Prioritize exiting if the door was previously used for exiting or not used for (index in exiting) { answer[index] = currentTime++ } for (index in entering) { answer[index] = currentTime++ } } else { // Prioritize entering if the door was previously used for entering for (index in entering) { answer[index] = currentTime++ } for (index in exiting) { answer[index] = currentTime++ } } // Update previous state for the next iteration previousState = if (exiting.isNotEmpty()) 1 else 0 i = j // Move to the next set of arrivals } return answer } }