这是我的 leetcode 问题代码 - Best Time to Buy and Sell Stock 3 我的 Golang 代码通过了 203/214 测试用例。对于大小为 10k 的特定输入数组,超出了我的时间限制。有任何想法吗?
基本算法如下:-
找到价格下降的指数,并忽略它之前的所有元素。例如,如果一个数组像 [5,4,3,2,1,2,3,4],这里的价格一直下降到第 4 个索引。
找到所有局部最小值和局部最大值。因为除非是局部最小值,否则您不想购买
如果只有一项有利可图的交易,即只有一项局部最小值和一项局部最大值,则将其返回。
通过检查以局部最小值买入和以局部最大值卖出的所有排列,找到所有有利可图的交易对。
返回最高交易对
我的代码:
func maxProfit(prices []int) int {
//trim left
temp, i := 0, 1
for ; i < len(prices) && prices[i] <= prices[temp]; i += 1 {
temp = i
}
if i == len(prices) {
return 0
}
i -= 1
//find all local lows and highs
localLows := []int{i}
localHighs := []int{}
for j := i + 1; j < len(prices)-1; j += 1 {
if prices[j] >= prices[j+1] {
for prices[j] == prices[j+1] {
j += 1
if j == len(prices)-1 {
break
}
}
localHighs = append(localHighs, j)
for ; j < len(prices)-1 && prices[j] >= prices[j+1]; j++ {
fmt.Print(j, " j")
}
fmt.Println()
localLows = append(localLows, j)
}
}
if prices[len(prices)-1] > prices[len(prices)-2] {
localHighs = append(localHighs, len(prices)-1)
}
fmt.Println(localLows, localHighs)
//if only one transaction, return that
if len(localHighs) == 1 {
return prices[localHighs[0]] - prices[localLows[0]]
}
//find all profitable transaction pairs
maxProfit := 0
for j := 0; j < len(localHighs); j += 1 {
for k := j; k < len(localHighs); k += 1 {
if prices[localHighs[k]]<prices[localLows[j]]{
continue
}
transaction1 := int(prices[localHighs[k]] - prices[localLows[j]])
for l := k + 1; l < len(localHighs); l++ {
for m := l; m < len(localHighs); m++ {
if prices[localHighs[m]]<prices[localLows[l]]{
continue
}
斯蒂芬大帝
ITMISS
随时随地看视频慕课网APP
相关分类