“Encontre subarray com dada soma” Respostas de código

Encontre subarray com dada soma

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;
    }
}
Mero

Encontre subarray com dada soma

import java.util.*;

public class FindSubarrayWithGivenSum1 {
	static int findSubarray(int[] arr,int n,int sum){
		int start =0;
		int end = 1;
		int curr_sum= arr[0];

		while(end <=n){
			while(curr_sum>sum && start < end-1){
				curr_sum-=arr[start];
				start++;
			}

			if(curr_sum == sum){
				System.out.println("Subarray found at "+start+" "+(end-1));
				return 1;
			}

			if(end < n){
				curr_sum+=arr[end];
			}
			end++;
		}
		System.out.println("no subarray found.");
		return 0;

	}

	public static void main(String[] args){
		int[] arr = {1, 4, 20, 3, 10, 5};
		int n = arr.length;
		int s = 33;
		findSubarray(arr,n,s);
	}
}
Aayush

Subarray com dado soma python

Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elements 
from 1st position to 5th position
is 15.
Shah Anzar

Respostas semelhantes a “Encontre subarray com dada soma”

Perguntas semelhantes a “Encontre subarray com dada soma”

Mais respostas relacionadas para “Encontre subarray com dada soma” em Java

Procure respostas de código populares por idioma

Procurar outros idiomas de código