【Array】Subarray with given sum

Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements.

Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.

Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= Ai <= 1010

Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5

Explanation :
Testcase1: sum of elements from 2nd position to 4th position is 12
Testcase2: sum of elements from 1st position to 5th position is 15

/*package whatever //do not write package name here */

import java.util.*;
import java.lang.*;
import java.io.*;


class GFG {
	public static void main (String[] args) {
		//code
		Scanner s = new Scanner(System.in);
		
		int testNum = s.nextInt(); //testcaseNum
		
		for (int i = 0; i < testNum; i++) {
		 int n = s.nextInt(); //arr.length
		int sum = s.nextInt(); //arr.sum   
		int[] arr = new int[n];
		for(int j = 0; j < n; j++) {
		    arr[j] = s.nextInt();
		}
		subArraySum(arr,n,sum);
		}
	}
	static void subArraySum(int[] arr, int n, int sum) {
	    int curr_sum, i , j;
	    //pick a starting point
	    for(i = 0; i < n; i++) {
	        curr_sum = arr[i];
	        
	        //try all subarrays starting with 'i'
	        for(j = i + 1; j <= n; j++) {
	            if(curr_sum == sum) {
	                int p = j - 1; //sum found between indexes i ~ p
	                System.out.println("sum of elements from " + i +"nd position to " + p +"th position is " + curr_sum);
	            }
	            if(curr_sum > sum || j==n) break;
	            curr_sum = curr_sum + arr[j];
	        }
	    }
	}
}

链接地址

For Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Your Output is:
sum of elements from 1nd position to 3th position is 12
sum of elements from 3nd position to 4th position is 12
sum of elements from 0nd position to 4th position is 15
sum of elements from 3nd position to 5th position is 15
sum of elements from 6nd position to 7th position is 15
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值