
QW 是一个回合制游戏的玩家,今天他决定去打怪。
QW 在一场战斗中会碰到 n 个怪物,每个怪物有攻击力 atk[i],每回合结束时如果第 i 个怪物还活着,就会对 QW 造成 atk[i] 的伤害。 QW 只能在每回合开始时击杀一个怪物,请帮 QW 出他打完所有怪物最少需要损失多少生命值。
n, atk[i] <= 100000
答案可能超过 int 范围
示例
样例 1:
输入:atk = [19,3]
输出:3
样例 2:
输入:atk = [1,3,2,5]
输出:102. 解题
class Solution {
public:
/**
* @param atk: the atk of monsters
* @return: Output the minimal damage QW will suffer
*/
long long getAns(vector<int> &atk) {
// Write your code here
sort(atk.rbegin(), atk.rend());
int n = atk.size();
vector<long long> tailsum(n+1, 0);
for(int i = n-1; i >= 0; --i)
tailsum[i] = tailsum[i+1]+atk[i];
long long life = 0;
for(int i = 1; i < n; ++i)
life += tailsum[i];//后序活着的怪兽 攻击的生命值之和
return life;
}
};151ms C++
class Solution {
public:
/**
* @param atk: the atk of monsters
* @return: Output the minimal damage QW will suffer
*/
long long getAns(vector<int> &atk) {
// Write your code here
sort(atk.rbegin(), atk.rend());
int n = atk.size();
long long life = 0;
for(int i = 1; i < n; ++i)
life += 1LL*i*atk[i];
return life;
}
};