Answers for "subarray with given sum problem solution gfg"

0

Subarray with given sum in c++

/*
    Geeks For Geeks
    link problem: https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1/?page=1&difficulty[]=0&status[]=unsolved&sortBy=submissions#
*/

class Solution
{
    public:
    //Function to find a continuous sub-array which adds up to a given number.
    vector<int> subarraySum(int arr[], int n, long long s)
    {
        // Your code here
   
	   vector<int> ans;
	   int sum = 0;
	   for (int i = 0; i < n; i++)
	   {
	      sum = 0;
		  for (int j = i; j < n; j++)
		   {
		      sum += arr[j];
			  if (sum == s)
			  {
				 ans.push_back(i + 1);
				 ans.push_back(j + 1);
				 return ans;
		       }
		       else if (sum > s)
			   {
			      break;
			   }
		       else
		       {
			      continue;
		       }
	    	}
    	}
    	ans.push_back(-1);
    	return ans;
    }
};
Posted by: Guest on April-17-2022
0

find subarray with given sum

import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;

public class FindSubArr {
    public static void main(String[] args) {
        int [] arr = {0,1,2,3,4,5,6,9,2,1,1,1,10,2,2,2};
        int s = 6 ;
        int [] sub = findLongestSubArray( arr,s);
        System.out.println("longest SubArray Range ==> "+Arrays.toString(sub));

    }

    public static int[] findLongestSubArray(int [] arr, int s){

        int[] result = new int[]{-1};
        int sum=0,left=0,right=0;

        while(right < arr.length){
            sum += arr[right];
            while(left < right && sum > s){
                sum -= arr[left++];
            }
            if(sum == s && (result.length == 1 || result[1] - result[0] < right - left)){
                result = new int[]{left + 1, right +1};
            }
            right++;
        }
        return result;
    }
}
Posted by: Guest on August-06-2021

Code answers related to "subarray with given sum problem solution gfg"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language