Find Score of an Array After Marking All Elements

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.

Example 1
Inputnums = [2,1,3,4,5,2]
Output7
The selected unmarked values are 1, then 2, then 4, giving a total score of 1 + 2 + 4 = 7.
Example 2
Inputnums = [2,3,5,1,3,2]
Output5
The selected unmarked values are 1, then the left-most 2, then the remaining 2, giving a total score of 1 + 2 + 2 = 5.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate