算法3:找出股票买入、卖出的最大利;例如股票每天的价格为{10, 8, 9, 11, 12, 9, 8, 7, 10, 9, 8}

分析

该算法可以是n的时间复杂度
p[temp] = p[0]
遍历数组如果p[i]比p[temp]小temp = i,否则找到temp买入的最大利润,最大利vmax如果比val大则把val=vmax。

func maxProfit(p []int) (int, int, int) {
	temp, start, end, val := 0, 0, 0, 0
	for i := range p {
		if p[temp] > p[i] {
			temp = i
		} else if val < p[i]-p[temp] {
			val = p[i] - p[temp]
			start = temp
			end = i
		}
	}
	return start, end, val
}

你可能感兴趣的:(算法3:找出股票买入、卖出的最大利;例如股票每天的价格为{10, 8, 9, 11, 12, 9, 8, 7, 10, 9, 8})