Find the Sub | Python 3 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 ; Driver Code
import sys NEW_LINE def findSubArray ( arr , n ) : NEW_LINE INDENT min_sum = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum = arr [ i ] NEW_LINE if ( min_sum > abs ( curr_sum ) ) : NEW_LINE INDENT min_sum = abs ( curr_sum ) NEW_LINE start = i NEW_LINE end = i NEW_LINE DEDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT curr_sum = curr_sum + arr [ j ] NEW_LINE if ( min_sum > abs ( curr_sum ) ) : NEW_LINE INDENT min_sum = abs ( curr_sum ) NEW_LINE start = i NEW_LINE end = j NEW_LINE DEDENT DEDENT DEDENT p = [ start , end ] NEW_LINE return p NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 5 , 4 , - 6 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE point = findSubArray ( arr , n ) NEW_LINE print ( " Subarray ▁ starting ▁ from ▁ " , end = " " ) NEW_LINE print ( point [ 0 ] , " to " , point [ 1 ] ) NEW_LINE DEDENT