You are given an array nums consisting of positive integers.
Starting with score = 0, apply the following algorithm:
-
Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
-
Add the value of the chosen integer to
score
.
-
Mark the chosen element and its two adjacent elements if they exist.
-
Repeat until all the array elements are marked.
Return the score you get after applying the above algorithm.
Function Signature
def find_score(nums: list[int]) -> int:
Rules
-
The adjacent elements of index
i
are indices
i - 1
and
i + 1
, when they are inside the array. The first and last elements have only one neighbor (a one-element array has none).
-
Neighbors are marked whether or not they were already marked. Marks are never removed, and a marked element is never chosen.
-
Ties between equal unmarked values always go to the smallest index, so the score is unique.
Constraints
-
1 <= nums.length <= 10^5
-
1 <= nums[i] <= 10^6
Examples
Input: nums = [2,1,3,4,5,2]
Output: 7
Pick index 1 (value 1) and mark indices 0, 1 and 2, so the score is 1. Pick index 5 (value 2) and mark indices 4 and 5, so the score is 3. The only unmarked element left is index 3 (value 4), which brings the score to 7.
Input: nums = [2,3,5,1,3,2]
Output: 5
Pick index 3 (value 1) and mark indices 2, 3 and 4, so the score is 1. Pick index 0 (value 2) and mark indices 0 and 1, so the score is 3. Pick index 5 (value 2) and mark it, so the score is 5.
Input: nums = [2,1,1,2,9]
Output: 3
The two 1s tie, so index 1 goes first and marks indices 0 to 2. Index 3 (value 2) is then the smallest unmarked element, and marking it also covers index 4, so the 9 is never added. Choosing index 2 first would have produced 12 instead.