121. 买卖股票的最佳时机
题目地址:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
题目描述
实现思路:
首先阅读样例,我以为直接找出最小值和最大值做差就行,但是分析这个样例 :
[ 2 , 5 , 1 , 3]
后,我们可以发现数组的最小值是1,但是得到最大利润是在2的时候买入,5的时候卖出。
因此就想到,从前往后遍历数组,并且维护一个最小价格(其实是局部最小价格),和一个最大利润(其实是局部利润和上次局部利润取最大值得到)
代码:
class Solution {
public int maxProfit(int[] prices) {
//1 <= prices.length <= 10^5
//0 <= prices[i] <= 10^4
int maxVal = 0;
int minPrice = 100000;
for(int i = 0 ; i < prices.length ; i++){
if(prices[i] < minPrice){ //找到局部最小值
minPrice = prices[i];
}else{
int cur_maxVal = prices[i] - minPrice;//局部最大利润
//和上个局部最大利润做比较,如果利润大于上个局部最大利润则更新
maxVal = cur_maxVal > maxVal ? cur_maxVal : maxVal;
}
}
return maxVal;
}
}