Find the Sub | Java program to find subarray with sum closest to 0 ; Function to find the subarray ; Pick a starting point ; Consider current starting point as a subarray and update minimum sum and subarray indexes ; Try all subarrays starting with i ; update minimum sum and subarray indexes ; Return starting and ending indexes ; Drivers code
class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static Pair findSubArray ( int arr [ ] , int n ) { int start = 0 , end = 0 , min_sum = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = arr [ i ] ; if ( min_sum > Math . abs ( curr_sum ) ) { min_sum = Math . abs ( curr_sum ) ; start = i ; end = i ; } for ( int j = i + 1 ; j < n ; j ++ ) { curr_sum = curr_sum + arr [ j ] ; if ( min_sum > Math . abs ( curr_sum ) ) { min_sum = Math . abs ( curr_sum ) ; start = i ; end = j ; } } } Pair p = new Pair ( start , end ) ; return p ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , - 5 , 4 , - 6 , - 3 } ; int n = arr . length ; Pair point = findSubArray ( arr , n ) ; System . out . println ( " Subarray ▁ starting ▁ from ▁ " + point . first + " ▁ to ▁ " + point . second ) ; } }