Skip to content

Commit 18009d0

Browse files
committed
Added Find Score of an Array After Marking All Elements
1 parent ed0ddc6 commit 18009d0

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
use std::cmp::Reverse;
2+
use std::collections::BinaryHeap;
3+
use std::collections::HashSet;
4+
5+
/// You are given an array `nums` consisting of positive integers.
6+
///
7+
/// Starting at `score = 0`, apply the following algorithm:
8+
///
9+
/// * Choose the smallest integer of the array that is not marked. If there is a tie, choose the
10+
/// one with the smallest index.
11+
///
12+
/// * Add the value of the chosen integer to `score`.
13+
///
14+
/// * Mark the chosen element and its two adjacent elements if they exist.
15+
///
16+
/// * Repeat until all the array elements are marked.
17+
///
18+
/// Return the score you get after applying the above algorithm.
19+
struct Solution;
20+
21+
impl Solution {
22+
23+
pub fn find_score(nums: Vec<i32>) -> i64 {
24+
let n = nums.len();
25+
26+
let mut marked: HashSet<usize> = HashSet::new();
27+
let mut mins: BinaryHeap<Reverse<(i32, usize)>> = BinaryHeap::new();
28+
let mut sum = 0;
29+
30+
for i in 0..n {
31+
let item = (nums[i], i);
32+
mins.push(Reverse(item));
33+
}
34+
35+
while !mins.is_empty() && marked.len() < n {
36+
let current = mins.pop().unwrap().0;
37+
let value = current.0;
38+
let index = current.1;
39+
if !marked.contains(&index) {
40+
marked.insert(index);
41+
sum += value as i64;
42+
43+
if index > 0 {
44+
marked.insert(index - 1);
45+
}
46+
if index < n-1 {
47+
marked.insert(index + 1);
48+
}
49+
}
50+
}
51+
52+
sum
53+
}
54+
55+
}
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::Solution;
60+
61+
#[test]
62+
fn example_1() {
63+
let nums = vec![2, 1, 3, 4, 5, 2];
64+
let result = Solution::find_score(nums);
65+
assert_eq!(result, 7);
66+
}
67+
68+
#[test]
69+
fn example_2() {
70+
let nums = vec![2,3,5,1,3,2];
71+
let result = Solution::find_score(nums);
72+
assert_eq!(result, 5);
73+
}
74+
75+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,8 @@ pub mod count_the_number_of_fair_pairs; // 2563 ✓
891891

892892
pub mod kth_largest_sum_in_a_binary_tree; // 2583 ✓
893893

894+
pub mod find_score_of_an_array_after_marking_all_elements; // 2593 ✓
895+
894896
pub mod remove_trailing_zeros_from_a_string; // 2710 ✓
895897
pub mod difference_of_number_of_distinct_values_on_diagonals; // 2711 ✓
896898
pub mod minimum_cost_to_make_all_characters_equal; // 2712

0 commit comments

Comments
 (0)