mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
@ -188,7 +188,40 @@ class Solution:
|
||||
```
|
||||
|
||||
Go:
|
||||
```golang
|
||||
//贪心算法
|
||||
func maxProfit(prices []int) int {
|
||||
var sum int
|
||||
for i := 1; i < len(prices); i++ {
|
||||
// 累加每次大于0的交易
|
||||
if prices[i]-prices[i-1] > 0 {
|
||||
sum += prices[i]-prices[i-1]
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
```
|
||||
|
||||
```golang
|
||||
//确定售卖点
|
||||
func maxProfit(prices []int) int {
|
||||
var result,buy int
|
||||
prices=append(prices,0)//在price末尾加个0,防止price一直递增
|
||||
/**
|
||||
思路:检查后一个元素是否大于当前元素,如果小于,则表明这是一个售卖点,当前元素的值减去购买时候的值
|
||||
如果不小于,说明后面有更好的售卖点,
|
||||
**/
|
||||
for i:=0;i<len(prices)-1;i++{
|
||||
if prices[i]>prices[i+1]{
|
||||
result+=prices[i]-prices[buy]
|
||||
buy=i+1
|
||||
}else if prices[buy]>prices[i]{//更改最低购买点
|
||||
buy=i
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
Javascript:
|
||||
```Javascript
|
||||
|
@ -151,7 +151,24 @@ class Solution:
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```golang
|
||||
func wiggleMaxLength(nums []int) int {
|
||||
var count,preDiff,curDiff int
|
||||
count=1
|
||||
if len(nums)<2{
|
||||
return count
|
||||
}
|
||||
for i:=0;i<len(nums)-1;i++{
|
||||
curDiff=nums[i+1]-nums[i]
|
||||
//如果有正有负则更新下标值||或者只有前一个元素为0(针对两个不等元素的序列也视作摆动序列,且摆动长度为2)
|
||||
if (curDiff > 0 && preDiff <= 0) || (preDiff >= 0 && curDiff < 0){
|
||||
preDiff=curDiff
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
```
|
||||
|
||||
Javascript:
|
||||
```Javascript
|
||||
|
@ -146,6 +146,23 @@ class Solution:
|
||||
return res
|
||||
```
|
||||
Go:
|
||||
```golang
|
||||
//排序后,局部最优
|
||||
func findContentChildren(g []int, s []int) int {
|
||||
sort.Ints(g)
|
||||
sort.Ints(s)
|
||||
|
||||
// 从小到大
|
||||
child := 0
|
||||
for sIdx := 0; child < len(g) && sIdx < len(s); sIdx++ {
|
||||
if s[sIdx] >= g[child] {//如果饼干的大小大于或等于孩子的为空则给与,否则不给予,继续寻找选一个饼干是否符合
|
||||
child++
|
||||
}
|
||||
}
|
||||
|
||||
return child
|
||||
}
|
||||
|
||||
|
||||
Javascript:
|
||||
```Javascript
|
||||
|
Reference in New Issue
Block a user