通过万岁!!!
java代码——基础
class Solution {
public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
int maxcurrProfit = Integer.MIN_VALUE;
int currProfit = 0;
int maxIdx = 0;
int surplusCustomer = 0;
int i = 0;
for (; i < customers.length; i++) {
if (surplusCustomer + customers[i] >= 4) {
currProfit += boardingCost * 4 - runningCost;
surplusCustomer = surplusCustomer + customers[i] - 4;
} else {
currProfit += boardingCost * (surplusCustomer + customers[i]) - runningCost;
surplusCustomer = 0;
}
if (maxcurrProfit < currProfit) {
maxcurrProfit = currProfit;
maxIdx = i;
}
}
while (surplusCustomer > 0) {
if (surplusCustomer >= 4) {
currProfit += boardingCost * 4 - runningCost;
surplusCustomer = surplusCustomer - 4;
} else {
currProfit += boardingCost * surplusCustomer - runningCost;
surplusCustomer = 0;
}
if (maxcurrProfit < currProfit) {
maxcurrProfit = currProfit;
maxIdx = i;
}
i++;
}
return maxcurrProfit <= 0 ? -1 : maxIdx + 1;
}
}
java代码——优化
class Solution {
public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
int maxProfit = Integer.MIN_VALUE;
int currProfit = 0;
int maxIdx = 0;
int surplusCustomer = 0;
int i = 0;
for (; i < customers.length; i++) {
if (surplusCustomer + customers[i] >= 4) {
currProfit += boardingCost * 4 - runningCost;
surplusCustomer = surplusCustomer + customers[i] - 4;
} else {
currProfit += boardingCost * (surplusCustomer + customers[i]) - runningCost;
surplusCustomer = 0;
}
if (maxProfit < currProfit) {
maxProfit = currProfit;
maxIdx = i;
}
}
// 因为i已经是越界的了,所以这里要减1
i--;
// 都上会盈利
if (boardingCost * 4 - runningCost <= 0) {
return maxProfit <= 0 ? -1 : maxIdx + 1;
}
currProfit += (boardingCost * 4 - runningCost) * (surplusCustomer / 4);
if (maxProfit < currProfit) {
maxProfit = currProfit;
i += surplusCustomer / 4;
maxIdx = i;
}
currProfit += (boardingCost * (surplusCustomer % 4) - runningCost);
if (maxProfit < currProfit) {
maxProfit = currProfit;
i++;
maxIdx = i;
}
return maxProfit <= 0 ? -1 : maxIdx + 1;
}
}