Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 28, 2018 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/d0390435d5c3bbaa7fa149b1479f70a1 to your computer and use it in GitHub Desktop.
Save jianminchen/d0390435d5c3bbaa7fa149b1479f70a1 to your computer and use it in GitHub Desktop.
Code from a friend to solve the float number with operators - maximum number for [1, 12, -3] is 37.
package google;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class NumbersWithOperators {
char[] ops = {'+', '-', '*', '/'};
public double GetMaxNumber(double[] nums){
if(nums == null || nums.length == 0){
return 0;
}
List<Double> list = helper(nums, 0, nums.length - 1);
double maxDouble = Double.MIN_VALUE;
for(double ele : list){
maxDouble = ele > maxDouble ? ele : maxDouble;
}
return maxDouble;
}
private List<Double> helper(double[] nums, int start, int end){
List<Double> rst = new LinkedList<>();
if(start == end){
rst.add(nums[start]);
}
else if(start + 1 == end){
List<Double> l1 = helper(nums, start, start);
List<Double> l2 = helper(nums, end, end);
rst = getCombinationResult(l1, l2);
}
else{
Set<Double> set = new HashSet<>();
for(int pos = start; pos <= end - 1; pos++){
List<Double> l1 = helper(nums, start, pos);
List<Double> l2 = helper(nums, pos + 1, end);
set.addAll(getCombinationResult(l1, l2));
}
rst.addAll(set);
}
return rst;
}
private List<Double> getCombinationResult(List<Double> l1, List<Double> l2){
Set<Double> set = new HashSet<>();
for(Double d1 : l1){
for(Double d2 : l2){
set.addAll(operate(d1, d2));
}
}
return new LinkedList<>(set);
}
private List<Double> operate(double num1, double num2){
Set<Double> set = new HashSet<>();
for(char op : ops){
switch (op){
case '+':
set.add(num1 + num2);
case '-':
set.add(num1 - num2);
case '*':
set.add(num1 * num2);
case '/':
if(num2 != 0){
set.add(num1 / num2);
}
}
}
return new LinkedList<>(set);
}
public static void main(String[] args){
NumbersWithOperators test = new NumbersWithOperators();
double[] nums = {1, 12, -3};
double rst = test.GetMaxNumber(nums);
System.out.println(rst);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment