2 - 推公式贪心
贪心问题之推公式问题。
练习题
2244. 完成所有任务需要的最少轮数 - 力扣(LeetCode)
问题可以转换为:每轮可以把 c
减少 2 或 3,问把 c
减少到 0 最少要几轮?例如 c = 10
时,10 = 3 + 3 + 2 + 2
要 4 轮。贪心的想,我们要尽量多减少 3,然后才减少 2。
int minimumRounds(vector<int>& tasks) { sort(tasks.begin(), tasks.end()); int ans = 0; for (int i = 0; i < tasks.size(); ++i) { int tmp = tasks[i], cnt = 1; while (i + 1 < tasks.size() && tasks[i + 1] == tmp) { cnt++; i++; } while (cnt >= 3) { if (cnt == 4) break; cnt -= 3; ans++; } while (cnt >= 2) { cnt -= 2; ans++; } if (cnt) return -1; } return ans; }