1. class Solution {
    2. public int maxProfit(int[] prices) {
    3. // 只要今天不是最低点,我们就尝试卖!是最低点,尝试买入。
    4. int minBuyPrice = Integer.MAX_VALUE;
    5. int maxProfile = 0;
    6. for (int i = 0; i < prices.length; i++) {
    7. if (prices[i] < minBuyPrice) {
    8. // 第一次进入一定会尝试买入,但是后面只有价格更低才会尝试买入
    9. minBuyPrice = prices[i];
    10. } else if (maxProfile < prices[i] - minBuyPrice) {
    11. // 当天不是最低加个,尝试卖出,看能否得到最大利润。
    12. // 这里会判断当天可得利润能否超过最大利润,超过,则卖出。
    13. maxProfile = prices[i] - minBuyPrice;
    14. }
    15. }
    16. // 包含了不交易的情况,因为一直进入不到那个else if的循环中
    17. return maxProfile;
    18. }
    19. }