题解 | #买卖股票的最好时机(二)#
买卖股票的最好时机(二)
https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9
package com.hhdd.dp;
/**
* @Author huanghedidi
* @Date 2022/8/7 17:11
*/
public class 买卖股票的最好时机2 {
public static void main(String[] args) {
int[] arr = {8, 9, 2, 5};
int res = maxProfit(arr);
System.out.println("res = " + res);
}
public static int maxProfit(int[] prices) {
// write code here
int ans = 0;
// 标识是否购买
boolean buyFlg = false;
int buyPrice = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
if (i + 1 < prices.length) {
// 预知明天的价格
if (prices[i + 1] > prices[i] && !buyFlg) {
// 明天涨价 且没有买过 今天就得买
buyPrice = prices[i];
buyFlg = true;
} else if (prices[i + 1] < prices[i] && buyFlg) {
// 明天降价 且买过 则得在今天卖掉
ans += prices[i] - buyPrice;
buyFlg = false;
}
} else {
// 这里是最后一天的逻辑
if (buyFlg) {
// 最后一天还持有,说明看好最后一天是涨价的
ans += prices[i] - buyPrice;
buyFlg = false;
}
}
}
return ans;
}
}
腾讯成长空间 5960人发布
