2593. Find Score of an Array After Marking All Elements #949
-
Topics: You are given an array Starting with
Return the score you get after applying the above algorithm. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can simulate the marking process efficiently by using a sorted array or priority queue to keep track of the smallest unmarked element. So we can use the following approach: Plan:
Let's implement this solution in PHP: 2593. Find Score of an Array After Marking All Elements <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function findScore($nums) {
$n = count($nums);
$score = 0;
$marked = array_fill(0, $n, false);
$heap = [];
// Build a min-heap with values and their indices
for ($i = 0; $i < $n; $i++) {
$heap[] = [$nums[$i], $i];
}
// Sort the heap based on values, and on index if values are tied
usort($heap, function($a, $b) {
if ($a[0] === $b[0]) {
return $a[1] - $b[1];
}
return $a[0] - $b[0];
});
// Process the heap
foreach ($heap as $entry) {
list($value, $index) = $entry;
// Skip if already marked
if ($marked[$index]) {
continue;
}
// Add the value to the score
$score += $value;
// Mark the current and adjacent elements
$marked[$index] = true;
if ($index > 0) {
$marked[$index - 1] = true;
}
if ($index < $n - 1) {
$marked[$index + 1] = true;
}
}
return $score;
}
// Example usage:
$nums1 = [2, 1, 3, 4, 5, 2];
$nums2 = [2, 3, 5, 1, 3, 2];
echo findScore($nums1) . "\n"; // Output: 7
echo findScore($nums2) . "\n"; // Output: 5
?> Explanation:
This solution meets the constraints and works efficiently for large inputs. |
Beta Was this translation helpful? Give feedback.
We can simulate the marking process efficiently by using a sorted array or priority queue to keep track of the smallest unmarked element. So we can use the following approach:
Plan:
nums
and initialize variables for the score and marking status.(value, index)
to manage ties based on the smallest index.marked
array to track whether an element and its adjacent ones are marked.