Reducing Dishes

hard array dp greedy sorting

Problem

satisfaction[i] is the like-coefficient of dish i. Choose any subset and serve them in any order; total = Σ time × satisfaction (time starts at 1). Maximize total.

Inputsatisfaction = [-1,-8,0,5,-9]
Output14
Drop -8, -9; serve -1,0,5 → 1×-1 + 2×0 + 3×5 = 14.

def max_satisfaction(satisfaction):
    a = sorted(satisfaction)
    suf = total = 0
    for x in reversed(a):
        if suf + x <= 0: break
        suf += x; total += suf
    return total
function maxSatisfaction(satisfaction) {
  const a = satisfaction.slice().sort((x, y) => x - y);
  let suf = 0, total = 0;
  for (let i = a.length - 1; i >= 0; i--) {
    if (suf + a[i] <= 0) break;
    suf += a[i]; total += suf;
  }
  return total;
}
class Solution {
    public int maxSatisfaction(int[] s) {
        Arrays.sort(s);
        int suf = 0, total = 0;
        for (int i = s.length - 1; i >= 0; i--) {
            if (suf + s[i] <= 0) break;
            suf += s[i]; total += suf;
        }
        return total;
    }
}
int maxSatisfaction(vector& s) {
    sort(s.begin(), s.end());
    int suf = 0, total = 0;
    for (int i = (int)s.size() - 1; i >= 0; i--) {
        if (suf + s[i] <= 0) break;
        suf += s[i]; total += suf;
    }
    return total;
}
Time: O(n log n) Space: O(1)