https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150

go

package leetcode150

import (
    "testing"
)

func TestMaxProfit(t *testing.T) {
    prices := []int{2, 1, 2, 0, 1}
    res := maxProfit(prices)
    println(res)
}

func maxProfit(prices []int) int {
    if len(prices) <= 1 {
        return 0
    }

    maxP := 0
    minVal := prices[0]
    for i := 1; i < len(prices); i++ {
        if prices[i] < minVal {
            minVal = prices[i]
        } else {
            if prices[i]-minVal > maxP {
                maxP = prices[i] - minVal
            }
        }
    }

    return maxP
}

java

package leetcode150;

public class a7_121_maxProfit {
    public int maxProfit(int[] prices) {
        if (prices.length == 1) {
            return 0;
        }
        int maxP = 0;
        int minVal = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < minVal) {
                minVal = prices[i];
            } else {
                if (prices[i] - minVal > maxP) {
                    maxP = prices[i] - minVal;
                }
            }
        }
        return maxP;
    }
}