Medium
You are given an array nums
consisting of positive integers.
Starting with score = 0
, apply the following algorithm:
score
.Return the score you get after applying the above algorithm.
Example 1:
Input: nums = [2,1,3,4,5,2]
Output: 7
Explanation: We mark the elements as follows:
Example 2:
Input: nums = [2,3,5,1,3,2]
Output: 5
Explanation: We mark the elements as follows:
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106
import java.util.PriorityQueue
class Solution {
fun findScore(nums: IntArray): Long {
var ans: Long = 0
val pq = PriorityQueue { a: IntArray, b: IntArray ->
if (a[0] == b[0]
) a[1] - b[1] else a[0] - b[0]
}
val vis = BooleanArray(nums.size)
for (i in nums.indices) {
pq.offer(intArrayOf(nums[i], i))
}
while (pq.isNotEmpty()) {
val it = pq.poll()
if (!vis[it[1]]) {
vis[it[1]] = true
ans += it[0].toLong()
if (it[1] > 0) {
vis[it[1] - 1] = true
}
if (it[1] < nums.size - 1) {
vis[it[1] + 1] = true
}
}
}
return ans
}
}