fork download
  1. fun main() {
  2. val t = readLine()!!.toInt()
  3.  
  4. repeat(t) {
  5. val (n, c) = readLine()!!.split(" ")
  6. val s = readLine()!!
  7. val len = n.toInt()
  8.  
  9. var maxWait = 0
  10. var nextGreen = -1
  11.  
  12. // Find the index of all green lights in the sequence
  13. val greenIndices = mutableListOf<Int>()
  14. for (i in 0 until len) {
  15. if (s[i] == 'g') {
  16. greenIndices.add(i)
  17. }
  18. }
  19.  
  20. // Calculate the minimal distance from any given point to the next green light
  21. for (i in 0 until len) {
  22. if (s[i] == c[0]) {
  23. // Find the first green after or at current index
  24. val nextGreenIndex = greenIndices.firstOrNull { it >= i } ?: (greenIndices[0] + len)
  25. val distance = nextGreenIndex - i
  26. maxWait = maxOf(maxWait, distance)
  27. }
  28. }
  29.  
  30. println(maxWait)
  31. }
  32. }
  33.  
Success #stdin #stdout 0.14s 40892KB
stdin
6
5 r
rggry
1 g
g
3 r
rrg
5 y
yrrgy
7 r
rgrgyrg
9 y
rrrgyyygy
stdout
3
0
2
4
1
4