:: Kotlin :: Binary Search
Code\n\nclass Solution {\n    fun earliestSecondToMarkIndices(nums: IntArray, changeIndices: IntArray): Int {\n        val n = nums.size\n        val m = change
# Code\n```\nclass Solution {\n    fun earliestSecondToMarkIndices(nums: IntArray, changeIndices: IntArray): Int {\n        val n = nums.size\n        val m = changeIndices.size\n        val sum = nums.sum()!!\n\n        for (i in 0 until m) {\n            changeIndices[i] -= 1\n        }\n\n        fun isPossible(idx: Int): Boolean {\n            val last = IntArray(n){ -1 }\n\n            for (i in 0 .. idx) {\n                val j = changeIndices[i]\n                last[j] = i\n            }\n\n            var marked = 0\n            var store = 0\n            for (i in 0 .. idx) {\n                val j = changeIndices[i]\n                if (last[j] == i) {\n                    if (store < nums[j]) return false\n                    marked += 1\n                    store -= nums[j]\n                } else {\n                    store += 1\n                }\n            }\n            // println("${idx} ${marked == n}")\n            return marked == n\n        }\n\n        var left = 0\n        var right = m - 1\n\n        while (left < right) {\n            val mid = left + (right - left) / 2\n            // println("${left} ${mid} ${right}")\n\n            if (isPossible(mid)) {\n                right = mid\n            } else {\n                left = mid + 1\n            }\n        }\n\n        if (left == m - 1 && isPossible(m - 1)) return m\n        return if (left == m - 1) -1 else left + 1\n    }\n}\n```
['Kotlin']