LeetCode 第208场周赛
第二题 经营摩天轮的最大利润
题目描述:
写题感受:
这是我第一次参加力扣的周赛,题目给我直接的感觉是长,难读,我理解题意都是拿用例套进题目去理解。毕竟,我是渣渣一个,第一题因为我想在代码上偷懒,加之编码经验不足,改来改去就到了11点,结果发现就是一个小问题,emmmm。。。
第二题我在12:00之前还差3个用例就可以通过。在此题中,我不够深入地理解题意,思考中脑海中有一丝灵感,但是总是抓不住。鉴于时间问题,我就草草按多种情况讨论写好代码,给的用例没错,提交过了133个用例,错了3个。然后一通乱改,emmm,还是3个过不了。后来请教同学,发现思路可能错了,同学大致跟我说了他的思路后,自己修改了一下成功通过了。
写代码的感受:将写物理题模拟事物运动的能力和将具体问题提炼成数学公式的数学能力结合起来,来写代码。果然,“学好数理化,走遍天下都不怕”,此乃前辈之真理也!
代码(一为注释版,二为未注释版):
一:
class Solution {
public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
int waitPeople = 0,historyPeople = 0,maxProfit = 0,minStep = 0,flag = -1;//用简明的英语定义变量
int n = customers.length;
if(boardingCost * 4 <= runningCost){//"油钱"大于等于"车费",利润不为正,跑个锤子
return flag;
}else{
for(int i = 0; i < n || waitPeople > 0;i++){//如果customers数组每个都小于等于4,n次可以上舱完,如果每个都比4大,n次就上不完了,需要用waitPeople>0来控制摩天轮的轮转了
if(i < n){//统计出要坐摩天轮的人数
waitPeople = waitPeople + Integer.valueOf(customers[i]);
}
if(waitPeople > 4){//模拟上舱的过程,等待人数减少,上舱人数增加
historyPeople = historyPeople + 4;
waitPeople = waitPeople - 4;
}else{
historyPeople = historyPeople + waitPeople;
waitPeople = 0;
}
int profit = (historyPeople * boardingCost) - ((i+1)*runningCost);//计算利润,看赚了多少
if(profit > maxProfit){//在每一次人上舱之后,比较上次和这次的利润大小
maxProfit = profit;
minStep = i+1;//i初值为0,要加1
}
}
if(maxProfit > 0){//利润为正且最大时,返回最小轮转次数
return minStep;
}else{
return flag;
}
}
}
}
二:
class Solution {
public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
int waitPeople = 0,historyPeople = 0,maxProfit = 0,minStep = 0,flag = -1;
int n = customers.length;
if(boardingCost * 4 <= runningCost){
return flag;
}else{
for(int i = 0; i < n || waitPeople > 0;i++){
if(i < n){
waitPeople = waitPeople + Integer.valueOf(customers[i]);
}
if(waitPeople > 4){
historyPeople = historyPeople + 4;
waitPeople = waitPeople - 4;
}else{
historyPeople = historyPeople + waitPeople;
waitPeople = 0;
}
int profit = (historyPeople * boardingCost) - ((i+1)*runningCost);
if(profit > maxProfit){
maxProfit = profit;
minStep = i+1;
}
}
if(maxProfit > 0){
return minStep;
}else{
return flag;
}
}
}
}
结果: