Leetcode: 2383. Minimum Hours of Training to Win a Competition 赢得比赛需要的最少训练时长

You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively.

You are also given two 0-indexed integer arrays energy and experience, both of length n.

You will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available.

Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i].

Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one.

Return the minimum number of training hours required to defeat all n opponents.

思路:

1、先考虑energy,如果initialEnergy > sum(energy) 则不用训练

                 如果 initialEnergy < sum(energy) 则需要训练sum(energy) - initialEnergy + 1小时

2、再考虑经验, 遍历 ex:experience, 如果当前initialEnergy > ex,则不需要额外训练,且initialEnergy += ex;    如果当前initialEnergy > ex, 则需要额外训练ex - initialExperience + 1小时,且initialEnergy = initialEnergy + (额外训练的) (ex - initialExperience + 1) + (比赛赢获得的)ex = ex * 2 + 1

具体代码:

class Solution {
public:
    int minNumberOfHours(int initialEnergy, int initialExperience, vector<int>& energy, vector<int>& experience) {
        int myenergy = 0;
        int res = 0; 
        for(int en: energy) {
            myenergy += en;
        }
        if(initialEnergy <=  myenergy){
            res = myenergy - initialEnergy + 1;
        }
        for(int ex: experience) {
            if(initialExperience > ex) {
                initialExperience += ex;
            } else {
                res += ex - initialExperience + 1;
                initialExperience = ex * 2 + 1;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129487716