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,938 questions

51,875 answers

573 users

How to find the maximum length of a subarray having a sum equal to K in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Function maxSubArrayLenEqualsToK(ByVal arr As Integer(), ByVal k As Integer) As Integer
        Dim current As Integer = 0, len As Integer = 0
        Dim dict As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)()
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 1
            current += arr(i)

            If current = k Then
                len = i + 1
            ElseIf dict.ContainsKey(current - k) Then
                len = Math.Max(len, i - dict(current - k))
            End If

            If Not dict.ContainsKey(current) Then
                dict(current) = i
            End If
        Next

        Return len
    End Function

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



' run:
'
'  5
'

 



answered Feb 23, 2024 by avibootz
...