Skip to content

1402. Reducing Dishes 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int maxSatisfaction(vector<int>& satisfaction) {
    int ans = 0;
    int sumSatisfaction = 0;

    ranges::sort(satisfaction, greater<>());

    for (const int s : satisfaction) {
      sumSatisfaction += s;
      if (sumSatisfaction <= 0)
        return ans;
      ans += sumSatisfaction;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int maxSatisfaction(int[] satisfaction) {
    int ans = 0;
    int sumSatisfaction = 0;

    satisfaction = Arrays.stream(satisfaction)
                       .boxed()
                       .sorted(Collections.reverseOrder())
                       .mapToInt(Integer::intValue)
                       .toArray();

    for (final int s : satisfaction) {
      sumSatisfaction += s;
      if (sumSatisfaction <= 0)
        return ans;
      ans += sumSatisfaction;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxSatisfaction(self, satisfaction: list[int]) -> int:
    ans = 0
    sumSatisfaction = 0

    for s in sorted(satisfaction, reverse=True):
      sumSatisfaction += s
      if sumSatisfaction <= 0:
        return ans
      ans += sumSatisfaction

    return ans