My LeetCode grinding. Trying to do a problem a day.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.rs 1.1KB

12345678910111213141516171819202122232425262728
  1. use std::cmp;
  2. pub fn max_satisfaction(mut satisfaction: Vec<i32>) -> i32 {
  3. // First we want to sort the dishes, because the maximum like-time will come
  4. // when the last dishes are highest in number - then we just need to work out which ones to cull
  5. // there is one case that can probably be optimised: all negative (cook nothing)
  6. // but it might be easier to just build that into the starting logic
  7. satisfaction.sort_by(|a, b| b.cmp(a));
  8. let mut max = 0;
  9. let mut sum = 0; // sum will count how much will be added by multiplying the end of the arr
  10. // Now loop backwards over the array seeing if it makes things better to add dishes
  11. // Note: The array has been reversed, so it's actually going forwards, trippy right?
  12. for dish in satisfaction {
  13. let total = max + dish + sum; // This is the total if this dish was added
  14. if total > max {
  15. sum = sum + dish;
  16. max = total;
  17. } else {
  18. return max; // we can't do better, stop here
  19. }
  20. }
  21. return cmp::max(0, max);
  22. }
  23. pub fn main() {
  24. println!("Expected: 20");
  25. println!("Got: {}", max_satisfaction(vec![4, 3, 2]));
  26. }