0

How can I get the product of an integer array with a specific limit in Java?

Lets say:

  • array is not sorted
  • array may contain any number from -99 to 99.
  • the limit specified is 1000.(maxProduct<=1000)

e.g

int[] array = {-5,1,-1,0,10,-10,9,-2,1001};

int maxProduct = arr[0]*arr[2]*arr[4]*arr[5]*arr[6]*arr[7];
Panagiotis
  • 93
  • 1
  • 8

5 Answers5

0

if the array have neg numbers then you should have a negative (minimal) value too...

You can interate the array element by element in versions where no streams are avaliable...

int res = 1;
int max = 1000;
for(int i : array){
   res *= i;
   if(res>max) res = max;
}
System.out.println("Product: " +  res);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0
int max = 1000;
int res = 1;
for (int i : array) {
    if (i >= 0)
        res *= i;
    if (res >= max)
        res = max;
}

this will exclude negative numbers but takes in 0

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
  • if you multiply a number with 0 is 0. :) and you might need the negative numbers as they can produce a greater product. – Panagiotis Nov 15 '16 at 12:48
  • i know. if you dont want 0 in it you should add it to your question. you only say no negative numbers. if you dont want 0 just change `if (i >= 0)` to `if (i >= 1)` – XtremeBaumer Nov 15 '16 at 12:49
  • I need negative numbers as two negative numbers result positive and might be required for max product – Panagiotis Nov 15 '16 at 15:43
0
OptionalInt reduce = Arrays.stream(array).
                     filter(i -> i != 0).
                     reduce((a, b) -> a * b > 1000 ? 1000 : a * b);

System.out.println(reduce.getAsInt());

you can extend or remove the filte. Depending on your requirements ...

griFlo
  • 2,084
  • 18
  • 28
0

If i get it right you are looking for a subset of that array with a maximal product under a given limit and the output to be something like

arr[1]*arr[5]*arr[6]*arr[10]

is the subset with the max. product.

In order to do this you need first to get the powerset of your array, i.e. all possible subsets of your array and calculate the product of each subset checking if it is the maximal under a given limit. Beleow is an example how to do so:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class NewClass {

    public static void main(String[] args) {
        Integer[] array = {-5,1,-1,0,10,-10,9,-2,1001};
        List<Integer> list = Arrays.asList(array);
        Integer limit = 1000;

        List<List<Integer>> powerset = getPowerset(list);
        List<Integer> maxProdList = getMaxProduct(powerset,limit);
        Integer prod =1;
        for(Integer i : maxProdList){
           prod*=i; 
        }
        System.out.println("List: " + maxProdList );
        System.out.println("max product: " + prod );
    }

    //returns all possible subsets [[-5],[-5,1,9],[1,-1,1001][-5,1,-1,0,10] ... and so on]
    // see also http://stackoverflow.com/questions/1670862/obtaining-a-powerset-of-a-set-in-java
    public static List<List<Integer>> getPowerset(Collection<Integer> list) {
        List<List<Integer>> ps = new ArrayList<>();
        ps.add(new ArrayList<>());
        for (Integer item : list) {
          List<List<Integer>> newPs = new ArrayList<>();

          for (List<Integer> subset : ps) {
            newPs.add(subset);
            List<Integer> newSubset = new ArrayList<>(subset);
            newSubset.add(item);
            newPs.add(newSubset);
          }
          ps = newPs;
        }
        return ps;
    }

    public static List<Integer> getMaxProduct(List<List<Integer>> listOfLists, Integer limit){
        List<Integer> listOfMax = new ArrayList<>();
        Integer max = 1;
        for(List<Integer> list : listOfLists){
            Integer prod =1;
            for(Integer i : list){
               prod*=i; 
            }
            if(prod>max && prod<=limit){
                max=prod;
                listOfMax = list;
            }
        }
        return listOfMax;        
    }
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • hello eritrean, this is going to take a lot of time..what if i have an array of 100 numbers? Then I will have to check 100 possible ways. Thank you though for your help. – Panagiotis Nov 15 '16 at 15:48
0

Here is an idea, roughed out in pseudocode. I haven't tested it:

maxProduct <- 1000
maxRand <- 99
lowLimit <- 5

repeat
  num <- random(1, maxRand)
  add num to array
  maxProduct <- maxProduct DIV num
  maxRand <- minimum(maxRand, maxProduct)
until (maxRand < lowLimit)

if (maxRand > 0) add maxRand to array

I use DIV for integer division and maxRand is added to the array to get the final product closer to the original maxProduct. You can adjust lowLimit as needed. I was feeling lazy so I didn't bother with negative numbers, possibly pick 2, 4 or 6 array elements and switch their signs. As long as there is an even number of negatives then the final product will be positive.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • Hello rossum, that's okay. The array of integers will be used as input to the function so I will not have to "create" the numbers. – Panagiotis Nov 15 '16 at 15:53