Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need help getting my code to stop giving errors. I need to input the values exactly as shown in the picture. I keep getting

I need help getting my code to stop giving errors. I need to input the values exactly as shown in the picture. I keep getting an error message after inputting 14. can someone help?
This is the code:
import java.util.*;
class Main {
static class Pair {
int first;
int second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static Pair getCandidatePair(int[] A, int target){
HashSet set = new HashSet>();
for (int num : A){
int complement = target - num;
if (set.contains(complement)){
return new Pair(num, complement);
}
set.add(num);
}
return new Pair(0,0);
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Consume newline
for (int i =1; i = t; i++){
String[] statusAndSize = scanner.nextLine().split("");
int status = Integer.parseInt(statusAndSize[0]);
int size = Integer.parseInt(statusAndSize[1]);
int[] groceries = new int[size];
String[] groceriesString = scanner.nextLine().split("");
for (int j =0; j size; j++){
groceries[j]= Integer.parseInt(groceriesString[j]);
}
int target = scanner.nextInt();
scanner.nextLine(); // Consume newline
Pair pair;
if (status ==1){
pair = getCandidatePairSorted(groceries, target);
} else {
pair = getCandidatePair(groceries, target);
}
if (pair.first !=0 && pair.second !=0){
System.out.println("Test case #"+ i +": Spend "+ target +" dollars by buying the groceries with "+ Math.min(pair.first, pair.second)+" dollars and "+ Math.max(pair.first, pair.second)+" dollars.");
} else {
System.out.println("Test case #"+ i +": No way you can spend exactly "+ target +" dollars.");
}
}
}
static Pair getCandidatePairSorted(int[] A, int target){
int left =0, right = A.length -1;
while (left right){
int sum = A[left]+ A[right];
if (sum == target){
return new Pair(A[left], A[right]);
} else if (sum target){
left++;
} else {
right--;
}
}
return new Pair(0,0);
}
}{(])[
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

how to return my books

Answered: 1 week ago