Question

# There are N blocks, numbered from 0 to N-1, arranged in a row. A couple of...

import java.util.Arrays;
import java.util.Scanner;

public class Solution {
public static int solution(int[] blocks) {
int longestDistance = 0;
int[] sortedBlocks = Arrays.copyOf(blocks,blocks.length);
Arrays.sort(sortedBlocks);
/*
* int i; for(i=0;i<blocks.length;i++) { if(sortedBlocks[0]==blocks[i]) { break;
* } } if(i>blocks.length/2) { if(i-1>0) { if(i+1<blocks.length) { if(i-2>0 &&
* blocks[i-2]!=blocks[i-1]) { longestDistance=(i+1)-(i-1)+1; }else if(i-2>0 &&
* blocks[i-2]==blocks[i-1]) { longestDistance=(i+1)-(i-2)+1; } } } }
*/

for(int n =0;n<blocks.length;n++) {
if(blocks.length == 2) {
longestDistance = 1-0+1;
break;
}

int m;
for( m =0;m<blocks.length;m++) {
if(sortedBlocks[n]==blocks[m]) {
break;
}
}
if(blocks.length == 3) {
if(m > 0 && m < blocks.length-1 ) {
if(blocks[m-1]>blocks[m] && blocks[m+1]>blocks[m]) {
longestDistance = 2-0+1;
}
else if(blocks[m-1]>blocks[m] && blocks[m+1]<blocks[m]) {
longestDistance = 1-0+1;

}else {
longestDistance = 1-0+1;
}}else if(m==0) {
if(blocks[m]>blocks[m+1] && blocks[m+1]>blocks[m+2]) {
longestDistance = 2-0+1;
}else {
longestDistance = 1-0+1;
}
}else {
if(blocks[m-2]>blocks[m-1] && blocks[m-1]>blocks[m]) {
longestDistance = 2-0+1;
}else {
longestDistance = 1-0+1;
}

}

break;
}
if(m > 0 && m < blocks.length-1 ) {

if(m-1>=0) {
if(m+1<blocks.length) {
if(m-2>0 && blocks[m-2]!=blocks[m-1]) {
longestDistance=(m+1)-(m-1)+1;
}else if(m-2>0 && blocks[m-2]>=blocks[m-1]) {
longestDistance=(m+1)-(m-2)+1;
}else if(m-2 < 0) {

if(m+1<=blocks.length-1 && blocks[m+1]>blocks[m]) {
longestDistance=(m+1)-(m-1)+1;
if(m+2<=blocks.length-1 && blocks[m+2]>blocks[m+1]) {
longestDistance=(m+2)-(m-1)+1;

}
}
}
}
}

break;

}
else {

continue;
}
}

/*
* int j; for(j=0;j<blocks.length;j++) {
* if(sortedBlocks[blocks.length/2]==blocks[i]) { break; }
*/

return longestDistance;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of blocks : \n");
int numberOfBlocks = scanner.nextInt();
if(numberOfBlocks>=2 && numberOfBlocks <= 200000) {
int[] blockArray = new int[numberOfBlocks];
for(int j=0;j<numberOfBlocks;j++) {
System.out.println("Enter height of "+j+ " block");
blockArray[j] = scanner.nextInt();
}
int longestDistance = solution(blockArray);
System.out.println("Longest distance between the frogs : "+ longestDistance);
}
}

}

#### Earn Coins

Coins can be redeemed for fabulous gifts.

##### Need Online Homework Help?

Most questions answered within 1 hours.