Skip to content

Commit

Permalink
greedy
Browse files Browse the repository at this point in the history
better solution is to build result by adding new dishes
  • Loading branch information
HerringtonDarkholme committed Apr 24, 2020
1 parent 780a074 commit 68f36b1
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 1402_reducing_dishes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
impl Solution {
pub fn max_satisfaction(mut dishes: Vec<i32>) -> i32 {
satisfaction(dishes)
}
}

fn satisfaction(mut dishes: Vec<i32>) -> i32 {
dishes.sort();
let positive_sum: i32 = dishes.iter().filter(|&&n| n > 0).sum();
let negative: Vec<i32> = dishes.iter().filter(|&&n| n < 0).cloned().collect();
let mut i = 0;
loop {
let diff = negative[i..].iter().sum::<i32>().abs();
if diff > positive_sum {
i += 1;
} else {
break;
}
}
dishes[i..].iter().enumerate().map(|(i, &k)| (i as i32 + 1) * k).sum()
}

0 comments on commit 68f36b1

Please sign in to comment.