Skip to content

Commit

Permalink
Calculate the minimum possible product in an array of 2 numbers
Browse files Browse the repository at this point in the history
A one dimensional array has been given with range of all integers i.e. from negatives to positives and you need to find a pair of numbers whose product is the least possible one in the entire array.
  • Loading branch information
GeekNandy authored Aug 26, 2021
0 parents commit be77854
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Data Structures/Arrays/Searches/Linear Search/MinProduct.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.arrays.sorting;

public class MinProduct {

static int calcMinProduct(int[] arr) {

int len = arr.length;
if(len < 2) return Integer.MAX_VALUE;
else {
int m = Integer.MAX_VALUE;
int sm = Integer.MAX_VALUE;
int h = Integer.MIN_VALUE;
int sh = Integer.MIN_VALUE;

for(int i = 0; i < len; i++) {
// calc highest & second highest
if(arr[i] > h) {
sh = h;
h = arr[i];
}
else if(arr[i] > sh) {
sh = arr[i];
}

// calc lowest & second lowest
if(arr[i] < m) {
sm = m;
m = arr[i];
}
else if(arr[i] < sm) {
sm = arr[i];
}
}

int prod = m * h; // 11
if(prod > h * sh) { // 99
prod = h * sh;
}
else if(prod > m * sm) { // 2
prod = m * sm;
}

return prod;
}

}

public static void main(String[] args) {
int[] arr = new int[] {2,4,6,8,9,1,5,11};
System.out.println(calcMinProduct(arr));
}

}

0 comments on commit be77854

Please sign in to comment.