首页 > 编程语言 >贪心算法_摆动序列

贪心算法_摆动序列

时间:2022-12-10 11:11:06浏览次数:41  
标签:10 End 示例 序列 算法 摆动 wiggleMaxLength 贪心

'示例 1:
'输入: [1,7,4,9,2,5]
'输出: 6
'解释: 整个序列均为摆动序列
'示例 2:
'输入: [1,17,5,10,13,15,10,5,16,8]
'输出: 7
'解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。
'示例 3:
'输入: [1,2,3,4,5,6,7,8,9]
'输出: 2

Sub 贪心算法_摆动序列()
    nums1 = Array(1, 7, 4, 9, 2, 5)
    nums2 = Array(1, 17, 5, 10, 13, 15, 10, 5, 16, 8)
    nums3 = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
    res = wiggleMaxLength(nums3)
    Debug.Print (res)
End Sub

Public Function wiggleMaxLength(nums)
    If UBound(nums) <= 1 Then wiggleMaxLength = UBound(nums): Exit Function
    curdiff = 0
    prediff = 0
    count = 1
    For i = 1 To UBound(nums)
        curdiff = nums(i) - nums(i - 1)
        If (curdiff > 0 And prediff <= 0) Or (curdiff < 0 And prediff >= 0) Then
            count = count + 1
            prediff = curdiff
        End If
    Next
    wiggleMaxLength = count
End Function

 

标签:10,End,示例,序列,算法,摆动,wiggleMaxLength,贪心
From: https://www.cnblogs.com/eyunkeji/p/16971272.html

相关文章