We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 06b57f5 commit 279da08Copy full SHA for 279da08
1402-reducing-dishes.js
@@ -3,11 +3,15 @@
3
* @return {number}
4
*/
5
const maxSatisfaction = function (satisfaction, max = 0) {
6
- satisfaction.sort((a, b) => b - a)
7
- for (let j = 1; j <= satisfaction.length; ++j) {
8
- let next = 0
9
- for (let i = 0, k = j; i < j; ++i, --k) next += satisfaction[i] * k
10
- max = Math.max(max, next)
+ satisfaction.sort((a, b) => a - b)
+ let res = 0
+ let total = 0
+ let len = satisfaction.length
+ // "We'll keep doing this as long as satisfaction[i] + total > 0" === satisfaction[i] > -total
11
+ // It is because the current running sum needs to be greater than 0 otherwise, it would decrease res.
12
+ for (let i = len - 1; i >= 0 && satisfaction[i] > -total; i--) {
13
+ total += satisfaction[i]
14
+ res += total
15
}
- return max
16
+ return res
17
0 commit comments