Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Can someone please tell me why I ' m getting an array error for the following test case? 3 1 6 3 6 7 9

Can someone please tell me why I'm getting an array error for the following test case?
3
163679
10
03163
11
0432-743910
14
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);
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored 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

Recommended Textbook for

C++ Database Development

Authors: Al Stevens

1st Edition

1558283579, 978-1558283572

More Books

Students also viewed these Databases questions