How to find the maximum sum of a subarray in VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Function maxSubArray(ByVal arr As Integer()) As Integer
        Dim maxSum As Integer = Integer.MinValue
        Dim currentSum As Integer = 0
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 1
            currentSum = Math.Max(arr(i), currentSum + arr(i))
            maxSum = Math.Max(currentSum, maxSum)
        Next

        Return maxSum
    End Function

    Public Shared Sub Main(ByVal args As String())
		' 4 + -1 + -1 + 2 + 3 = 7
        Dim arr As Integer() = New Integer() {1, -2, 2, -3, 4, -1, -1, 2, 3, -5, 4}
	
        Console.WriteLine(maxSubArray(arr))
    End Sub
End Class

 

 
' run:
'
' 7
'

 

 



answered Feb 25, 2024 by avibootz

Related questions

1 answer 98 views
2 answers 203 views
1 answer 144 views
1 answer 55 views
...