买股票的最佳时机

 

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/

func maxProfit(prices []int) int {
    n:=len(prices)
    vis:=make([]int,n+1)
    for i:=n-1;i>=0;i--{
       if prices[i]>=vis[i+1]{
            vis[i]=prices[i]
        }else{
            vis[i]=vis[i+1]
        }
    }

    ans:=0
    for i:=range prices{
        if vis[i+1]-prices[i]>ans{
            ans=vis[i+1]-prices[i]
        }
    }
    return ans
}

 

 

 

 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/

func maxProfit(prices []int) int {
    ans:=0
    n:=len(prices)
    for i:=1;i<n;i++{
        if prices[i]>prices[i-1]{
            ans=ans+prices[i]-prices[i-1]
        }
    }
    return ans
}

 

posted @ 2022-06-17 14:20  知道了呀~  阅读(52)  评论(0编辑  收藏  举报