题解 | #牛群买卖计划III#
牛群买卖计划III
https://www.nowcoder.com/practice/47ce4c953769468e8b8b727af3cbebf5
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfitIII (int[] prices) {
//只有一天或空数组
if(prices.length<=1) return 0;
//利润
int profit=0;
//取最后一天,必然卖出
int sell = prices[prices.length-1];
//从后向前遍历
for(int i = prices.length-2;i>=0;i--){
// 价格小于卖出价格时计算利润
if(prices[i]<sell){
profit+=sell-prices[i];
}else{
// 价格大于或等于卖出价格时更改卖出价
sell=prices[i];
}
}
return profit;
}
}
面试高频TOP202 文章被收录于专栏
面试高频TOP202题解
查看11道真题和解析

