LeetCode-in-Java

2593. Find Score of an Array After Marking All Elements

Medium

You are given an array nums consisting of positive integers.

Starting with score = 0, apply the following algorithm:

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:

Solution

import java.util.PriorityQueue;

public class Solution {
    private static class Point {
        int idx;
        int val;

        Point(int idx, int val) {
            this.idx = idx;
            this.val = val;
        }
    }

    public long findScore(int[] arr) {
        PriorityQueue<Point> pq =
                new PriorityQueue<>((a, b) -> b.val == a.val ? a.idx - b.idx : a.val - b.val);
        int n = arr.length;
        boolean[] visited = new boolean[n];
        for (int i = 0; i < n; i++) {
            pq.add(new Point(i, arr[i]));
        }
        long ans = 0;
        while (!pq.isEmpty()) {
            Point p = pq.remove();
            int idx = p.idx;
            if (!visited[idx]) {
                ans += p.val;
                visited[idx] = true;
                if (idx - 1 >= 0 && !visited[idx - 1]) {
                    visited[idx - 1] = true;
                }
                if (idx + 1 < n && !visited[idx + 1]) {
                    visited[idx + 1] = true;
                }
            }
        }
        return ans;
    }
}