Smallest sum contiguous subarray | Set | Function to find the smallest sum contiguous subarray ; First invert the sign of the elements ; Apply the normal Kadane algorithm but on the elements of the array having inverted sign ; Invert the answer to get minimum val ; Driver Code
< ? php function smallestSumSubarr ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ arr [ $ i ] = - $ arr [ $ i ] ; $ sum_here = $ arr [ 0 ] ; $ max_sum = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ sum_here = max ( $ sum_here + $ arr [ $ i ] , $ arr [ $ i ] ) ; $ max_sum = max ( $ max_sum , $ sum_here ) ; } return ( -1 ) * $ max_sum ; } $ arr = array ( 3 , -4 , 2 , -3 , -1 , 7 , -5 ) ; $ n = sizeof ( $ arr ) ; echo " Smallest ▁ sum : ▁ " , smallestSumSubarr ( $ arr , $ n ) ; ? >