算法 买卖股票的最佳时机 II

给你一个整数数组prices,其中prices[i]表示某支股票第 i 天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候最多只能持有一股股票。你也可以先购买,然后在同一天出售。返回你能获得的最大利润 。

示例

 思路分析:通过观察以上案例发现这道题的意思应该知道每天股市的价格,所以我们要知道当天的股价是不是该轮最高值,先遍历数组找出最大值,但示例三是如何实现确定股价走势的且是不是只要第二天股价比第一天高就卖出,如何实现决定卖还是不卖

经过思考后发现可以用for循环嵌套循环实现大体思路,第一轮循环用来遍历,第二轮循环用来确定后面是否有高于当天股价的值,如果有就购入,没有就continue进行遍历下一天的股价,所以在内循环中需要排序找到最大值和当天股价进行比较,经过观察后如果想要获得最大利润就必须后面的股价大于当天股价时就卖出,接下来就要计算利润,因为如果第二天股价比当天高要当即卖出,所以还要和后一天比较,我的答案如下

func maxProfit(prices []int) int {
    var count int
    for i := 1; i < len(prices); i++ {
        max := prices[i]
        for j := 1; j < len(prices) - i + 1; j++ {
            if prices[j] > prices[j-1] {
                max = prices[j]
            }
        }
        if prices[i] > max {
            continue
        }
        if prices[i] > prices[i-1] {
            count = count + (prices[i] - prices[i-1]) 
        }
    }
    return count
}

但运行结果如下

 思考后发现是内循序的结束条件、当前股价对比处和max初值错了,改为如下代码

func maxProfit(prices []int) int {
    var count int
    for i := 1; i < len(prices); i++ {
        max := prices[i-1]
        for j := 1; j < len(prices); j++ {
            if prices[j] > prices[j-1] {
                max = prices[j]
            }
        }
        if prices[i-1] >= max {
            continue
        }
        if prices[i] > prices[i-1] {
            count = count + (prices[i] - prices[i-1]) 
        }
    }
    return count
}

运行后在测试[2,1,2,0,1]例子时,发现结果和预期不同,但思考后觉得逻辑没错

以下是答案

func maxProfit(prices []int) int {
	if len(prices) == 1 {
		return 0
	}
	res := 0
	minN := prices[0]
	for i := 1; i < len(prices); i++ {

		if prices[i-1] <= prices[i] {
			p := prices[i] - prices[i-1]
			res += p
			continue
		}
		if minN < prices[i] {

			minN = prices[i]
			continue
		}
		if prices[i] <= minN {
			minN = prices[i]
		}
	}
	return res
}

猜你喜欢

转载自blog.csdn.net/qq_47431008/article/details/130252849