Find the Sub | Javascript program to find subarray with sum closest to 0 ; Returns subarray with sum closest to 0. ; To consider the case of subarray starting from beginning of the array ; Store prefix sum with index ; Sort on the basis of sum ; Find two consecutive elements with minimum difference ; Update minimum difference and starting and ending indexes ; Return starting and ending indexes ; Driver code
class Prefix { constructor ( ) { this . sum = 0 ; this . index = 0 ; } } class Pair { constructor ( a , b ) { this . first = a ; this . second = b ; } } function findSubArray ( arr , n ) { let start = - 1 , end = - 1 , min_diff = Number . MAX_VALUE ; let pre_sum = new Array ( n + 1 ) ; for ( let i = 0 ; i < n + 1 ; i ++ ) pre_sum [ i ] = new Prefix ( ) ; pre_sum [ 0 ] . sum = 0 ; pre_sum [ 0 ] . index = - 1 ; for ( let i = 1 ; i <= n ; i ++ ) { pre_sum [ i ] . sum = pre_sum [ i - 1 ] . sum + arr [ i - 1 ] ; pre_sum [ i ] . index = i - 1 ; } pre_sum . sort ( function ( a , b ) { return a . sum - b . sum } ) ; for ( let i = 1 ; i <= n ; i ++ ) { let diff = pre_sum [ i ] . sum - pre_sum [ i - 1 ] . sum ; if ( min_diff > diff ) { min_diff = diff ; start = pre_sum [ i - 1 ] . index ; end = pre_sum [ i ] . index ; } } let p = new Pair ( start + 1 , end ) ; return p ; } let arr = [ 2 , 3 , - 4 , - 1 , 6 ] ; let n = arr . length ; let point = findSubArray ( arr , n ) ; document . write ( " " ) ; document . write ( point . first + " " + point . second ) ;