Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find the sum of the subarray which has the largest sum in VB.NET

2 Answers

0 votes
Imports System
				
Public Module Module1
	public Function max_subarray_sum(arr() as Integer) As Integer
		Dim max_sum As Integer = 0
        Dim max_till_i As Integer = 0
  
		For i As Integer = 0 To arr.Length - 1
            max_till_i = max_till_i + arr(i)
            max_till_i = Math.Max(max_till_i, 0)
			max_sum = Math.Max(max_sum, max_till_i)
		Next
  
        return max_sum
	End Function
	Public Sub Main()
		Dim arr() As Integer = {1, -2, 2, -3, 4, -1, -1, 2, 3, -5, 4}  '  4 - 1 - 1 + 2 + 3 = 7
 
        Console.Write(max_subarray_sum(arr))
	End Sub
End Module



' run:
'
' 7
' 

 



answered Jul 27, 2019 by avibootz
edited Apr 16, 2023 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Function max_subarray_sum(ByVal arr As Integer()) As Integer
        Dim sum As Integer = 0
        Dim max As Integer = arr(0)

        For Each val As Integer In arr
            sum += val
            max = Math.Max(sum, max)
            sum = Math.Max(sum, 0)
        Next

        Return max
    End Function

    Public Shared Sub Main()
        Dim arr As Integer() = {1, -2, 2, -3, 4, -1, -1, 2, 3, -5, 4}
	
        Console.Write(max_subarray_sum(arr))
    End Sub
End Class




' run:
'
'  7
'

 



answered Feb 23, 2024 by avibootz

Related questions

...