Farthest from zero
You are given an integer array A of size N
Your task is to print the farthest element from O. If there are multiple elements, print the number with the least value:
Example
Consider array A -1-5-2014]. So the element farthest from 0 is -5 which is at a distance of 5 to the left of 0.
Function description
Complete the solve function provided in the editor. This function takes the following 2 parameters and returns the farthest from O
• N Represents the size of the array.
• A Represents the array elements.
Input format
The first line contains a single integer N. denoting the size of the array A..
• The next line contains A integers denoting the elements of array A
Output format
1
3
scar
pr
Answers
Answer:
public class FarthestNumberFromZero {
public static void fnfz(int arr[], int N) {
int farthestDistance = Integer.MIN_VALUE;
for (int i = 0; i < N; i++) {
if (arr[i] < 0) {
if (farthestDistance <= Math.abs(arr[i]))
farthestDistance = arr[i];
} else {
farthestDistance = arr[i];
}
}
System.out.println(farthestDistance);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = { 5, -2, -3, -4, -5 };
fnfz(arr, 5);
}
}
Explanation:
Answer:
The program is implemented.
Explanation:
Given an array arr[] of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1.
Examples:
Input: arr[] = {3, 1, 5, 2, 4}
Output: 3 -1 4 -1 -1
arr[3] is the farthest smallest element to the right of arr[0].
arr[4] is the farthest smallest element to the right of arr[2].
And for the rest of the elements, there is no smaller element to their right.
Input: arr[] = {1, 2, 3, 4, 0}
Output: 4 4 4 4 -1
A brute force approach to this problem can be, keep a variable idx = -1 from beginning and for each element start traversing the same array from the backward upto (i+1)th index. And, if at any index j find smaller element from the current element, i.e. (a[i] > a[j]) break from the loop.
Below is the implementation of the above approach :
// Java implementation of the approach
class farthest{
// Function to find the farthest
// smaller number in the right side
static void farthest_min(int[] a, int n)
{
// To store minimum element
// in the range i to n
for (int i = 0; i < n; i++) {
// keeping the idx = -1 from beginning
int idx = -1;
for (int j = n - 1; j > i; j--) {
// if found any element smaller
if (a[i] > a[j]) {
// update that index and break
idx = j;
break;
}
}
System.out.print(idx + " ");
}
} // Driver code
public static void main(String[] args)
{
int[] a = { 3, 1, 5, 2, 4 };
int n = a.length;
farthest_min(a, n);
}
}