跳到主要内容

2383.赢得比赛需要的最少训练时长

链接:2383.赢得比赛需要的最少训练时长
难度:Easy
标签:贪心、数组
简介:返回击败全部 n 个对手需要训练的 最少 小时数目。

题解 1 - cpp

  • 编辑时间:2023-03-13
  • 内存消耗:10.9MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
int minNumberOfHours(int initialEnergy, int initialExperience, vector<int>& energy, vector<int>& experience) {
int res = 0, esum = initialExperience;
res += max(accumulate(energy.begin(), energy.end(), 0) - initialEnergy + 1, 0);
for (auto &e : experience) {
if (e >= esum) res += e - esum + 1, esum += e - esum + 1;
esum += e;
}
return res;
}
};

题解 2 - cpp

  • 编辑时间:2023-03-13
  • 执行用时:4ms
  • 内存消耗:10.8MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
int minNumberOfHours(int initialEnergy, int initialExperience, vector<int>& energy, vector<int>& experience) {
int res = 0;
for (int i = 0; i < energy.size(); i++) {
if (initialEnergy <= energy[i])
res += energy[i] - initialEnergy + 1, initialEnergy += energy[i] - initialEnergy + 1;
initialEnergy -= energy[i];
if (initialExperience <= experience[i])
res += experience[i] - initialExperience + 1, initialExperience += experience[i] - initialExperience + 1;
initialExperience += experience[i];
}
return res;
}
};

题解 3 - python

  • 编辑时间:2023-03-13
  • 执行用时:36ms
  • 内存消耗:14.9MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
res = 0
for i in range(len(energy)):
if initialEnergy <= energy[i]:
res += energy[i] - initialEnergy + 1
initialEnergy += energy[i] - initialEnergy + 1
initialEnergy -= energy[i]
if initialExperience <= experience[i]:
res += experience[i] - initialExperience + 1
initialExperience += experience[i] - initialExperience + 1
initialExperience += experience[i]
return res

题解 4 - rust

  • 编辑时间:2023-03-13
  • 内存消耗:2.2MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn min_number_of_hours(
mut initial_energy: i32,
mut initial_experience: i32,
energy: Vec<i32>,
experience: Vec<i32>,
) -> i32 {
let mut res = 0;
for i in 0..energy.len() {
if initial_energy <= energy[i] {
res += energy[i] - initial_energy + 1;
initial_energy += energy[i] - initial_energy + 1;
}
initial_energy -= energy[i];
if initial_experience <= experience[i] {
res += experience[i] - initial_experience + 1;
initial_experience += experience[i] - initial_experience + 1;
}
initial_experience += experience[i];
}
res
}
}