122 买卖股票最佳时机2
func maxProfit(prices []int) int {
// 思路,因为支持同一天买入卖出,所以利润最大应该是所有正利润的加总结果
var sum int
for i:=1; i<len(prices); i++ {
if prices[i] - prices[i-1] > 0 {
sum += prices[i] - prices[i-1]
}
}
return sum
}
55 跳跃游戏
func canJump(nums []int) bool {
// 思路,从跳跃起点开始找对应区间的覆盖范围,加上区间内最大的覆盖范围,如果大于等于列表长度,返回true
if len(nums) == 1 {
return true
}
cover := nums[0]
for i := 0 ; i <= cover; i++ {
if i + nums[i] > cover {
cover = i + nums[i]
}
if cover >= len(nums) - 1 {
return true
}
}
return false
}
45 跳跃游戏2
func jump(nums []int) int {
// 思考,贪心的思路应该是每次在可以条约的范围内找到最大的跳跃距离
if len(nums) == 1 {
return 0
}
var start, count int
for start + nums[start] < len(nums) - 1 {
start = next(nums, start)
count++
}
return count + 1
}
func next(nums []int, start int) int { // 传入数组区间,返回最远的下一个距离
var maxdis int = start + nums[start]
var max int = start
for i:=start; i <= start + nums[start] && i < len(nums); i++ {
//fmt.Println(i, max, maxdis)
if i + nums[i] > maxdis {
maxdis = i + nums[i]
max = i
}
}
//fmt.Println("=========")
return max
}
1005 k取反后最大和
func largestSumAfterKNegations(nums []int, k int) int {
// 思路,每次找最小值取反,然后最后加总
for i:=0; i<k; i++{
nums = nagationMin(nums)
}
var sum int
for _, v := range nums{
sum += v
}
return sum
}
func nagationMin (nums []int) []int {
var min int = math.MaxInt
var index int
for idx, v := range nums {
if v < min {
min = v
index = idx
}
}
nums[index] *= -1
return nums
}
标签:return,游戏,nums,int,随想录,start,func,跳跃
From: https://www.cnblogs.com/zhougongjin55/p/18356541