面试经典 150 题 (七)

从右往左遍历
class Solution {
public int maxProfit(int[] prices) {
Map<Integer, Integer> priceMap = new HashMap<Integer, Integer>();
Integer leftMaxNum = null;
for (int i = prices.length - 1; i >= 0; i--){
if (leftMaxNum == null || leftMaxNum < prices[i]){
leftMaxNum = prices[i];
}
priceMap.put(prices[i], leftMaxNum);
}
int maxMom = 0;
for (Map.Entry<Integer, Integer>price : priceMap.entrySet()){
if ((price.getValue() - price.getKey()) > maxMom){
maxMom = price.getValue() - price.getKey();
}
}
return maxMom;
}
}
不用hashMap版本
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1){
return 0;
}
int leftMaxPrices[] = new int[prices.length];
int leftMax = 0;
for (int i = prices.length - 1; i >= 0; i--){
if(prices[i] > leftMax){
leftMax = prices[i];
}
leftMaxPrices[i] = leftMax;
}
int maxPro = 0;
for (int i = 0; i < prices.length; i++){
if (maxPro < leftMaxPrices[i] - prices[i]){
maxPro = leftMaxPrices[i] - prices[i];
}
}
return maxPro;
}
}
从左向右,记录当前最小的价格
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1){
return 0;
}
int minPrice = prices[0];
int maxPro = 0;
for (int i = 1; i < prices.length; i++){
if (minPrice > prices[i]){
minPrice = prices[i];
}
if((prices[i] - minPrice) > maxPro){
maxPro = prices[i] - minPrice;
}
}
return maxPro;
}
}
浙公网安备 33010602011771号