LeetCode Best Time to Buy and Sell Stock

来源:互联网 发布:显微镜图像测量软件 编辑:程序博客网 时间:2024/06/10 13:21

原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Maximum Subarray相似,都是全局最优与局部最优问题。

维护一个局部最优解,和一个全局最优解, 先更新局部最优解, 要么是原来的局部最优加上i天与i-1天得差价,要么是0(i天股价没有i-1天高), 然后维护全局最优,最后返回全局最优。

AC Java:

public class Solution {    public int maxProfit(int[] prices) {        //采用局部最优和全局最优        if(prices == null || prices.length <= 1){            return 0;        }        int local = 0;        int global = 0;        for(int i = 1; i<prices.length; i++){            local = Math.max(local+prices[i]-prices[i-1],0);            global = Math.max(local,global);        }        return global;    }}

后面有多个进阶版本。

Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock IV


0 0
原创粉丝点击