首页 > 编程语言 >贪心算法_最大子序和

贪心算法_最大子序和

时间:2022-12-10 11:47:29浏览次数:40  
标签:count nums sum maxSubArray 算法 数组 子序 贪心

'给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
'示例: 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。


Sub 贪心算法_最大子序和()
    nums = Array(-2, 1, -3, 4, -1, 2, 1, -5, 4)
    res = maxSubArray(nums)
    Debug.Print (res)
End Sub

Public Function maxSubArray(nums)
    If UBound(nums) = 1 Then maxSubArray = nums(0): Exit Function
    sum = -1048576
    count = 0
    For i = 0 To UBound(nums)
        count = count + nums(i)
        sum = Application.Max(sum, count)
        If count <= 0 Then
            count = 0
        End If
    Next
    maxSubArray = sum
End Function

 

标签:count,nums,sum,maxSubArray,算法,数组,子序,贪心
From: https://www.cnblogs.com/eyunkeji/p/16971317.html

相关文章