File tree Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Original file line number Diff line number Diff line change 3
3
* @return {number }
4
4
*/
5
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 )
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
11
15
}
12
- return max
16
+ return res
13
17
}
You can’t perform that action at this time.
0 commit comments