|
| 1 | +// 2530. Maximal Score After Applying K Operations |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/maximal-score-after-applying-k-operations/ |
| 5 | +// |
| 6 | +// Tags: Array - Greedy - Heap (Priority Queue) |
| 7 | + |
| 8 | +use std::collections::BinaryHeap; |
| 9 | + |
| 10 | +struct Solution; |
| 11 | +impl Solution { |
| 12 | + /// Use a heap to get the largest value in each of the k iterations. Pop the largest value and |
| 13 | + /// add it to the result, then push ceil(x/3) into the heap. |
| 14 | + /// |
| 15 | + /// Time complexity: O(nlog(n)) - We build the heap from the input, then pop/push k values. |
| 16 | + /// Space complexity: O(n) - The heap. |
| 17 | + /// |
| 18 | + /// Runtime 34 ms Beats 33% |
| 19 | + /// Memory 4.11 MB Beats 100% |
| 20 | + pub fn max_kelements(nums: Vec<i32>, k: i32) -> i64 { |
| 21 | + let mut score = 0; |
| 22 | + let mut nums = BinaryHeap::from(nums); |
| 23 | + for _ in 0..k { |
| 24 | + if let Some(val) = nums.pop() { |
| 25 | + score += val as i64; |
| 26 | + nums.push((val + 2) / 3); |
| 27 | + } |
| 28 | + } |
| 29 | + score |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Tests. |
| 34 | +fn main() { |
| 35 | + let tests = [ |
| 36 | + (vec![10, 10, 10, 10, 10], 5, 50), |
| 37 | + (vec![1, 10, 3, 3, 3], 3, 17), |
| 38 | + ]; |
| 39 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 40 | + let mut success = 0; |
| 41 | + for (i, t) in tests.iter().enumerate() { |
| 42 | + let res = Solution::max_kelements(t.0.clone(), t.1); |
| 43 | + if res == t.2 { |
| 44 | + success += 1; |
| 45 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 46 | + } else { |
| 47 | + println!( |
| 48 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 49 | + i, t.2, res |
| 50 | + ); |
| 51 | + } |
| 52 | + } |
| 53 | + println!(); |
| 54 | + if success == tests.len() { |
| 55 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 56 | + } else if success == 0 { |
| 57 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 58 | + } else { |
| 59 | + println!( |
| 60 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 61 | + tests.len() - success |
| 62 | + ) |
| 63 | + } |
| 64 | +} |
0 commit comments