Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
 array arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} of size 10.a sub-array of size n and sum s, n and s both are user input values.

Print YES if there exists a subarray of size n and sum s in the array arr else print NO

Input

3 6
Output

YES


What I have tried:

import java.util.*;

public class Main {

    public static void solve(int []arr, int n, int s){
       
		int sum =0;
		int flag=0;
		for(int i=1; i<n; i++){
			for(int j=1; j<s; j++){
				for(int k=i; k<=j; k++){
					flag=1;
					sum = sum+arr[k];
					sum=arr[k];
				}
			}
				if(flag==1){
					System.out.print("YES");
					break;
				}
				else{
					System.out.print("NO");
					break;

			}
		}
    }

    public static void main(String[] args) throws Throwable {
        Scanner sc = new Scanner(System.in);
        int []arr={1,2,3,4,5,6,7,8,9,10};
        int n;
        n=sc.nextInt();
        int s;
        s=sc.nextInt();
        solve(arr, n, s);
    }
}
Posted
Updated 22-Dec-22 0:09am

1 solution

Java
flag=1;           // why are you setting this to 1 here?
sum = sum+arr[k];
sum=arr[k];       // you are overwriting the accumulated sum

Add a number to sum, then immediately overwrite it with the number. You need to think more about what your codse is supposed to be doing. Before you code it write down the steps that you need it to do, one by one. Note that you always set flag to 1, so you will always print "YES" at the end.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900