Skip to content

Commit 279da08

Browse files
authored
Update 1402-reducing-dishes.js
1 parent 06b57f5 commit 279da08

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

1402-reducing-dishes.js

+10-6
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33
* @return {number}
44
*/
55
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)
6+
satisfaction.sort((a, b) => a - b)
7+
let res = 0
8+
let total = 0
9+
let len = satisfaction.length
10+
// "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
1115
}
12-
return max
16+
return res
1317
}

0 commit comments

Comments
 (0)