美文网首页LeetCode By Go
[LeetCode By Go 63]121. Best Tim

[LeetCode By Go 63]121. Best Tim

作者: miltonsun | 来源:发表于2017-08-28 17:18 被阅读5次

    题目

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Example 1:

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

    Example 2:

    Input: [7, 6, 4, 3, 1]
    Output: 0
    In this case, no transaction is done, i.e. max profit = 0.

    解题思路

    最多只能买一次,那么就是找到Max{price[i] - min{price[0], ..., price[i-1]}, 0 }

    需要两个辅助变量,一个记录当前节点之前股票的最小值minPrice,然后将当前值currentPrice减去minPrice和全局最大利润maxProfit相比,如果大于maxProfit则更新

    代码

    maxProfit.go

    package _121_Best_Time2Buy_and_Sell_Stock
    
    func MaxProfit(prices []int) int {
        var maxProfit int
        var currentMin int
        len1 := len(prices)
    
        if len1 == 0 {
            return 0
        }
        currentMin = prices[0]
    
    
        for i := 1; i < len1; i++ {
            if maxProfit < prices[i] - currentMin {
                maxProfit = prices[i] - currentMin
            }
    
            if currentMin > prices[i] {
                currentMin = prices[i]
            }
        }
    
        return maxProfit
    }
    

    测试

    maxProfit_test.go

    package _121_Best_Time2Buy_and_Sell_Stock
    
    import "testing"
    
    func TestMaxProfit(t *testing.T) {
        var tests = []struct{
            input []int
            output int
        } {
            {[]int{}, 0},
            {[]int{7, 1, 5, 3, 6, 4}, 5},
            {[]int{7, 6, 4, 3, 1}, 0},
        }
    
        for _, v := range tests {
            ret := MaxProfit(v.input)
    
            if ret == v.output {
                t.Logf("pass")
            } else {
                t.Errorf("fail, want %+v, get %+v\n", v.output, ret)
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 63]121. Best Tim

        本文链接:https://www.haomeiwen.com/subject/vnugdxtx.html