How does the Math.max function work in this code?
calculating the max using math import - Stack Overflow
Can you use the Math.max() method for 4 values instead of 2?
Is Math.max(a,b) or (a>b)?a:b faster in Java? - Stack Overflow
Videos
class consecutiveOnes
{
public int findMaxConsecutiveOnes(int[] nums) { //constructor that accepts as an argument an int array called nums.
int maxHere = 0, max = 0; //int variable declarations initialized with zero.
for (int n : nums) //for each loop. for int n in nums array:
max = Math.max(max, maxHere = n == 0 ? 0 : maxHere +1); //ternary operator. max is assigned the math.max function (different use of max). max is the total max values consecutively. maxHere is the max value per n in the array.
// This says if the larger of the two values (max, maxHere)
// is zero, return zero and overwrite max with zero(this ensures the consecutive counter for 1 is reset), else increment maxHere by 1.
return max; //returns max
}
public static void main (String[] args)
{
consecutiveOnes co = new consecutiveOnes();
int nums[] = {1, 0, 1, 1, 1, 1};
//int n = nums.length;
System.out.println("number of consecutive ones are: " +co.findMaxConsecutiveOnes(nums));
}
}I understand that the Math.max function returns the highest of two values (in this case, the highest of max and maxHere). Included are comments of what I believe is happening. What I don't understand is why the Math.max function is not returning 2 for max when for example, n in the array is 1. Would it not be the case since maxHere is incrementing by 1?
My rationalization is if n = 1, and maxhere +1 or increments by 1, then maxHere = 2 and new max value is 2, but that would not make sense, especially because consecutive count would be 2 at the first run of the loop...
EDIT: I apologize for the confusion. The code runs fine, but I have a limited understanding of why the Math.max function is choosing maxHere = 1 for max and not maxHere = 2 when maxHere = n =1 since maxHere + 1 would execute.
I need to compare 4 values and determine which one is biggest.
Here is the openjdk code for Math.max() in Java:
Copypublic static int max(int a, int b) {
return (a >= b) ? a : b;
}
So, the code would probably be (almost) exactly the same speed.
(Lets be honest, if you are worrying about speed improvements at such a low level, you probably have far greater problems in your code.)
Math.max(a, b) is a static function (meaning no virtual call overhead) and will likely be inlined by the JVM to the same instructions as (a > b) ? a : b.