Skip to content

Instantly share code, notes, and snippets.

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/9ccc8c0c977232d5ca64b8bd0ba328d8 to your computer and use it in GitHub Desktop.
Save jianminchen/9ccc8c0c977232d5ca64b8bd0ba328d8 to your computer and use it in GitHub Desktop.
Float numbers and operators - Feb. 14, 2018 mock interview 10:00 pm
Given a list of float numbers, and four operators +, -, *, / with flat preference, find the maximum
value by inserting operator between each consecutive pair of numbers.
For example, given the array [1, 12, -3], the maximum number 33 can be found using 1 - 12 * (-3), since
all operators have flat preference, so 1 - 12 * (-3) will be handled from left to right, first operation
is 1 - 12 with value -11, and then second operation is -11 * (-3) = 33.
+ - * /
1 1? 1
12 12 -12
-3 9 10
1, 12, -3
Julia gave the hint:
First two number
1 + 12 = 13
1 - 12 = - 11
1 /12 = 1/12
1 * 12 = 12
The result first two number, brute force way, work with -3
[13, -3] -> another four options
[-11, -3] ->
[1/12. -3]->
[12, -3] ->
4 * 4 = 16
What should we do to reduce the problem space? Save four numbers, or three numbers or two numbers
or one number?
The interviewee took the hint, and decided to save max and min; and he started to write the optimal
solution.
int computeMax(int[] arr, char[] ops) {
int acc = arr[0];
Integer max = acc;
Integer min = acc;
for (int i = 1; i < arr.length; i++) {
int operand = arr[i];
int tmpMax = max;
int tmpMin = min;
for (char op : ops) {
int result1 = performOp(op, tmpMax, operand);
int result2 = performOp(op, tmpMin, operand);
max = Math.max(result1, result2);
min = Math.min(result1, result2);
}
}
return Math.max(max, min);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment