Check if a subarray exists with sum greater than the given Array | C ++ program to check if a subarray exists with sum greater than the given Array ; Function to check whether there exists a subarray whose sum is greater than or equal to sum of given array elements ; Initialize sum with 0 ; Checking possible prefix subarrays . If sum of them is less than or equal to zero , then return 1 ; again reset sum to zero ; Checking possible suffix subarrays . If sum of them is less than or equal to zero , then return 1 ; Otherwise return 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int subarrayPossible ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum <= 0 ) return 1 ; } sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( sum <= 0 ) return 1 ; } return 0 ; } int main ( ) { int arr [ ] = { 10 , 5 , -12 , 7 , -10 , 20 , 30 , -10 , 50 , 60 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( subarrayPossible ( arr , size ) ) cout << " Yes " << " STRNEWLINE " ; else cout << " No " << " STRNEWLINE " ; return 0 ; }