Maximum Sub Array | Practice | GeeksforGeeks

Find out the maximum sub-array of non negative numbers from an array.
The sub-array should be contiguous i.e., a sub-array created by choosing the second and fourth element and skipping the third element is invalid.
Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if sum(A) > sum(B).
Example:
A : [1, 2, 5, -7, 2, 3]
The two sub-arrays are [1, 2, 5] [2, 3].
The answer is [1, 2, 5] as its sum is larger than [2, 3]
NOTE 1: If there is a tie, then compare with segment's length and return segment which has maximum length.
NOTE 2: If there is still a tie, then return the segment with minimum starting index.
Example 1:
Input:
N = 3
A[] = {1, 2, 3}
Output: 1 2 3
Explanation: In the given array every
element is non-negative.

Example 2:
Input:
N = 2
A[] = {-1, 2}
Output: 2
Explanation: The only subarray [2] is
the answer.
 
Your Task:
Complete the function findSubarray() which takes the array a and the size of the array, n, as input parameters and returns an array representing the answer. If there is no subarray return an array of length 1 containing -1 only. You don't to print answer or take inputs.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
-105 ≤ A[i] ≤ 105
 
0
aasif23643 days ago
Easy and Intuitive C++ Solution 
vector<int> findSubarray(int a[], int n) {    vector<vector<int>>temp;    vector<int>arr;    for(int i=0 ; i<n ; i++){        if(a[i] >= 0){            arr.push_back(a[i]);        }        else{            temp.push_back(arr);            arr.clear();        }    }        if(!arr.empty()){        temp.push_back(arr);    }    int mx=0;    vector<int>res;        for(auto i : temp){        long long sum=0;        vector<int>t;        for(auto j : i){            t.push_back(j);            sum+=j;        }        if(mx < sum){            res.clear();            mx=sum;            res=t;        }    }        if(res.empty()){        res.push_back(-1);        return res;    }        return res;}
0
imranwahid4 days ago
Easy C++ solution
https://ide.geeksforgeeks.org/t49Nvd3d53
+2
manishbit232 weeks ago
C++ easy divide and conquer 
{
	    int i=0,j=0,mx=INT_MIN,start=0,end=0;
	    long long int sum=0;
	    vector<int> v;
	    while(j<n){
	        if(a[j]>=0){
	            sum+=a[j];
	            if(sum>mx){
	                mx=sum;
	                start=i,end=j;
	            }else if(sum==mx){
	                      if(j-i>end-start) start=i, end=j;
	            }
	        }
	        else i=j+1, sum=0;
	        j++;
	    }
	    
	    if(end==0 and a[end]<0) return {-1};
	    for(int p=start;p<=end;p++){
	        v.push_back(a[p]);
	    }
	    return v;
	}
0
cooljiit2 months ago
 ArrayList<Integer> findSubarray(int a[], int n) {      Long curSum=0l,prevSum=0l;      HashMap<Long,ArrayList<Integer>> h = new HashMap<>();     ArrayList<Integer> g=new ArrayList<>();      for(int i =0;i<n;i++){          if(a[i]>=0){          curSum+=a[i];             g.add(a[i]);          }else{              if(!h.containsKey(curSum)){                h.put(curSum,g);              }else{                  h.put(curSum,g.size()>h.get(curSum).size()?g:h.get(curSum));              }              g= new ArrayList<>();              curSum=0l;              continue;          }                }        if(!h.containsKey(curSum)){                h.put(curSum,g);              }              else {                  h.put(curSum,g.size()>h.get(curSum).size()?g:h.get(curSum));              }    //  System.out.println(h.size());      long max=0l;      for(Long w:h.keySet()){           if(max<w){               max=w;           }      }      if((h.size()==1 && h.containsKey(0))){           ArrayList<Integer> j=new ArrayList<>();           j.add(-1);          h.put(max,j);      }      //System.out.println("max :"+max);      if(max>0){      return h.get(max);      }else{          ArrayList<Integer> j=new ArrayList<>();           j.add(-1);                    return j;      }   }
0
0vlmr673m94qqyw8itwt1zs9vrdevuzx3dobwn0z2 months ago
 ArrayList<Integer> findSubarray(int a[], int n) {       ArrayList<Integer> arr=new ArrayList<Integer>();               int x=0,y=0, x1=0,y1=0;       boolean neg=false;       int negcount=0;       int max=Integer.MIN_VALUE;       int curmax=0;       for(int i=0;i<a.length;i++)       {              if(a[i]>=0){               if(neg){                   x1=i;y1=i;                 neg=false;                 }           curmax=curmax+a[i];            y1=i;           }           else{               ++negcount;               neg= true;               if(max<curmax)               {   max=curmax;                   x=x1;y=y1;               }               curmax=0;                         }         if(i==a.length-1){              if(max<curmax)               {   max=curmax;                   x=x1;y=y1;               }           }                  }       if(x==0&y==0)       {x=x1;y=y1;}              if(negcount==a.length)       { arr.add(-1);           return arr;       }       for(int i= x;i<=y;i++)       arr.add(a[i]);              return arr;   }
+3
noob_7232 months ago
#define ll long long 
vector<int> findSubarray(int a[], int n) {
    int i, j, s, e;
    ll cs, ms;
    s = e = i = j = cs = ms = 0;
    
    while(j < n) {
        if(a[j] >= 0) {
            cs += a[j];
            if(cs >= ms) {
                s = i;
                e = j;
                ms = cs;
            }
        }
        else {
            cs = 0;
            i = j + 1;
        }
        j++;
    }
    
    if(s == e && a[s] < 0) return {-1};
    vector<int> v;
    for(int i = s; i <= e; i++) {
        v.push_back(a[i]);
    }
    return v;
}
0
noob_723
This comment was deleted.
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.3 / 1.5 sec
 
bool check_positive(int a[],int n){      for(int i = 0; i < n; i++){          if(a[i] > 0){              return (true);          }      }      return (false);  }
vector<int> findSubarray(int a[], int n) {    if(!check_positive(a,n)){        return (vector<int>{-1});    }        int i = 0,j = 0;    long long int max_sum = 0;    long long int curr_sum = 0;        int s = 0, e = 0;        while(j < n){        if(a[j] >= 0){            curr_sum += a[j];            if(curr_sum >= max_sum){                s = i;                e = j;                max_sum = curr_sum;            }            j++;        }        else{            curr_sum = 0;            i = j+1;            j++;        }    }        vector<int> ans;    for(int i = s; i <= e; i++){        ans.push_back(a[i]);    }        if(!ans.size())        ans.push_back(-1);           return (ans);}
0
shvmsnju2 months ago
Python 3 solution (0.8 sec):
class Solution:

	def findSubarray(self,a, n):
    	flag = 0
    	for i in range(n):
    	    if a[i]>=0:
    	        flag = 1
    	if flag == 0:
    	    return [-1]
    	sum_prev,sum_curr,l,l1,r = 0,0,0,0,0
    	for i in range(n):
    	    if a[i]>=0:
    	        sum_curr += a[i]
    	    if(a[i]<0 or i==n-1):
    	        if (sum_curr>sum_prev) or (sum_prev==sum_curr and (i-l1+1)>(r-l)):
    	            sum_prev = sum_curr
    	            r = i
    	            l = l1
    	            if (i == n-1 and a[i]>=0):
    	                r+=1
    	        l1 = i+1
    	        sum_curr = 0
        return a[l:r]
+1
sudarshanp49123 months ago
EASY C++ SOLUTION: 
vector<int> findSubarray(int arr[], int n) 
	{
	    int i=0,j=0,mx=INT_MIN,start=0,end=0;
	    long long int sum=0;
	    vector<int> v;
	    
	    while(j<n)
	    {
	        if(arr[j]>=0)
	        {
	            sum+=arr[j];
	            if(sum>mx)
	            {
	                mx=sum;
	                start=i,end=j;
	            }
	            else if(sum==mx)
	            {
	                if(j-i>end-start)
	                {
	                    start=i;
	                    end=j;
	                }
	            }
	        }
	        else
	        {
	            i=j+1;
	            sum=0;
	        }
	        j++;
	    }
	    
	    if(end==0 and arr[end]<0)
	    return {-1};
	    
	    for(int a=start;a<=end;a++)
	    {
	        v.push_back(arr[a]);
	    }
	    return v;
	}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.