- any sequence of integers, such as 23 7 13 4 8 6. I want to define local minimums and maximums with the following rules:
- the first number in the sequence is a local minimum when the next number is greater
- the last number in the sequence is a local minimum when the previous number is greater
- the number in the sequence is a local minimum when it is less than the previous and next number
I can use the hasNextInt and getNextInt methods .
I am currently thinking of an algorithm. But I'm not sure if I understand the logic. First, I build a tuple and compare its numbers. For instance. I compare 23 and 7. 7 is a local minimum. What would I do then? Create a triple ? But which numbers have three, 23 7 13 or 13 4 8? I'm not sure.
Any ideas?
Update:
Let's say we save the left neighbor and the number in the middle of three numbers:
left middle current
0 0 23
23 0 7
23 7 13 <- you have a triple, compare => minimum 7
What will happen then? Set vars to 0 and start with the next number 4? Or save 7 on the left, 13 in the middle to have 4 as current?
Update (this code works):
int left = 0;
int center = 0;
while(hasNextInt()){
int current = getNextInt();
if((left != 0) && (center != 0)){
if(current > center && center < left){
System.out.println("Min: "+center);
left = center; center = current;
}else{
left = center; center = current;
}
}else if((left != 0) && (center == 0)){
if(left < current){
System.out.println("Min: "+left);
center = current;
}else{
center = current;
}
}else if((left == 0) && (center == 0)){
left = current;
}
}
if(left > center){
System.out.println("Min: "+center);
}
Thank you for your help!
source
share