0
点赞
收藏
分享

微信扫一扫

LeetCode-121-买卖股票的最佳时机

承蒙不弃 2021-09-28 阅读 73
LeetCode

买卖股票的最佳时机

解法一:动态规划
public class LeetCode_121 {
    public static int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int result = 0;
        int buyPrice = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] == buyPrice) {
                continue;
            } else if (prices[i] < buyPrice) {
                buyPrice = prices[i];
            } else {
                if (prices[i] - buyPrice > result) {
                    result = prices[i] - buyPrice;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] prices = new int[]{7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(prices));
    }
}
举报

相关推荐

0 条评论