2593. Find Score of an Array After Marking All Elements

Difficulty:
Related Topics:
Similar Questions:

Problem

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:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2].
- 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2].
Our score is 1 + 2 + 4 = 7.

Example 2:

Input: nums = [2,3,5,1,3,2]
Output: 5
Explanation: We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2].
- 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2].
Our score is 1 + 2 + 2 = 5.

Constraints:

Solution (Java)

class Solution {
     static class Pair {
        int element;
        int idx ;
        public Pair (int x , int y) {
            this.element = x;
            this.idx = y;
        }
    }
    public long findScore(int[] nums) {
        long score = 0;
        boolean[] vis = new boolean[nums.length];
        PriorityQueue<Pair> q = new PriorityQueue<>((a,b)->a.element==b.element?a.idx-b.idx:a.element-b.element);
        for (int i=0;i<nums.length;++i) {
            q.offer(new Pair(nums[i], i));
        }
        while(!q.isEmpty()) {
            Pair currPair = q.poll();
            if(!vis[currPair.idx]) {
                vis[currPair.idx]=true;
                score+=(long)currPair.element;
                if((currPair.idx+1)<nums.length) {
                    vis[currPair.idx+1]=true;
                }
                if((currPair.idx-1)>=0) {
                    vis[currPair.idx-1]=true;
                }
            }
        }
        return(score);
    }
}

Explain:

nope.

Complexity: