|
| 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 | +} |
0 commit comments