例题:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/
分析:
题目说了,某一天买入股票,未来任意一天卖出,只卖一次,求最大利润,i 尝试买入,j 尝试卖出。
站在上帝视角,我们能清楚地知道股票每一天的价格,一开始,我们假设从第0天买入股票,j 肯定要比 i 大,因为要在未来某一天卖出,i = 0, j = 1,这个时候股票是遇跌的,因此,我们尝试在股票跌的那一天买入,也就是 i = j,j++,如下图:
这时发现股票有涨幅,但不一定第 j 天卖出的利润最大,还需观察,先把第j天卖出的利润记录下来,接着 i 不变, j++,
此时到第j天卖出仍有涨,所以i不变,j++,一直找到最大利润
我们能发现一个规律:当遇到涨时,i不变,j++, 遇到跌时,i 变为 j, j++
代码实现:
package leetcodeup;
public class ShareslLeetcode121 {
public static int maxProfit(int[] prices) {
int i = 0;
int j = 1;
int max = 0;
while(j < prices.length){
if(prices[j] - prices[i] > 0){ //涨
max = Math.max(prices[j] - prices[i], max);
}else{ //跌
i = j;
}
j++;
}
return max;
}
public static void main(String[] args) {
System.out.println(maxProfit(new int[]{9, 3, 12, 1, 2, 3, 11}));
}
}