-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Calculate the minimum possible product in an array of 2 numbers
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
0 parents
commit be77854
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
53 changes: 53 additions & 0 deletions
53
Data Structures/Arrays/Searches/Linear Search/MinProduct.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
|
||
} |