增加新题目
This commit is contained in:
26
贪心算法/买卖股票的最佳时机/main.go
Normal file
26
贪心算法/买卖股票的最佳时机/main.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
|
||||
}
|
||||
func maxProfit(prices []int) int {
|
||||
minnum := 0
|
||||
res := 0
|
||||
|
||||
for i := 0; i < len(prices); i++ {
|
||||
if i == 0 {
|
||||
minnum = prices[i]
|
||||
res = 0
|
||||
continue
|
||||
}
|
||||
if prices[i] < minnum {
|
||||
minnum = prices[i]
|
||||
}
|
||||
tmpnum := prices[i] - minnum
|
||||
|
||||
if tmpnum > res {
|
||||
res = tmpnum
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
25
贪心算法/跳跃游戏/main.go
Normal file
25
贪心算法/跳跃游戏/main.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
|
||||
}
|
||||
|
||||
func canJump(nums []int) bool {
|
||||
maxstep := 0
|
||||
for i := 0; i < len(nums); i++ {
|
||||
if maxstep == 0 {
|
||||
maxstep = nums[i] + (i + 1)
|
||||
continue
|
||||
}
|
||||
if (i + 1) <= maxstep {
|
||||
tmp := nums[i] + (i + 1)
|
||||
if tmp > maxstep {
|
||||
maxstep = tmp
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
67
贪心算法/跳跃游戏II/main.go
Normal file
67
贪心算法/跳跃游戏II/main.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println(jump([]int{2, 3, 1, 1, 4}))
|
||||
}
|
||||
|
||||
func jump(nums []int) int {
|
||||
res := 0
|
||||
right := 2
|
||||
maxstep := 0
|
||||
|
||||
for i := 0; i < len(nums); i++ {
|
||||
if (i+1)+nums[i] > right {
|
||||
maxstep = (i + 1) + nums[i]
|
||||
}
|
||||
if (i + 1) == right {
|
||||
res++
|
||||
right = maxstep
|
||||
}
|
||||
if maxstep >= len(nums) {
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
//func jump(nums []int) int {
|
||||
// step := make([]int, len(nums))
|
||||
// res := 0
|
||||
// for i := 0; i < len(nums); i++ {
|
||||
// maxstep := 0
|
||||
// maxi := 0
|
||||
// for j := i + 1; j < i+nums[i]; j++ {
|
||||
// if j >= len(nums) {
|
||||
// break
|
||||
// }
|
||||
// if j == i+1 {
|
||||
// maxstep = nums[j]
|
||||
// maxi = j
|
||||
// continue
|
||||
// }
|
||||
// if nums[j] >= maxstep {
|
||||
// maxstep = nums[j]
|
||||
// maxi = j
|
||||
// }
|
||||
// }
|
||||
// step[i] = maxi
|
||||
// }
|
||||
// tmp := make([]int, len(nums))
|
||||
// copy(tmp, step)
|
||||
// for len(tmp) > 1 {
|
||||
// res++
|
||||
// num := tmp[0]
|
||||
// i := 0
|
||||
// for i < num {
|
||||
// tmp = tmp[1:]
|
||||
// i++
|
||||
// }
|
||||
// //fmt.Println("---", tmp)
|
||||
// }
|
||||
// //fmt.Println(step)
|
||||
// //fmt.Println(res)
|
||||
// return res
|
||||
//}
|
||||
Reference in New Issue
Block a user