Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected number of assignments to find maximum value in an array

In the following Java code:

int max = arr[0];
for (int i = 0; i < arr.length i++) {
    if (arr[i] > max) {
         max = arr[i];
    }
} 

How many times does the line max = arr[i]; run assuming that the array is unsorted.

like image 455
12345webster12345 Avatar asked Mar 26 '16 20:03

12345webster12345


People also ask

How to find the minimum and maximum number in an array?

Use For Each, Assign and If Statements to find the minimum and maximum number in an array of Int32 elements and print it. Note : You can instantiate the Array with {7, 5, 2, 4, 3, 9} or with your own values, as long as they are integers. Start the project as a sequence and define a variable of type Array of Int32 . You can name it “initArray”

What is the expected value of the array?

The expected value is also known as the expectation, mathematical expectation, EV, or first moment. Given an array, the task is to calculate the expected value of the array.

How to get max value of an array in JavaScript?

The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max. // This code is contributed by anuj_67.

How to find the largest element in an array?

Given an array, find the largest element in it. Example: The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max.


1 Answers

Expected valued can be computated via linearity of expectations. I could provide a more rigorous answer if this site supported MathJax.

The answer is sum 1/(n-i+1) for i = 1 to n = sum 1/i for i = 1 to n = O(log n) where n is the size of the array (assuming all elements of the array are distinct)

Warning, Math-sy part ahead.

The key idea is that if we assign each element a lexicographical index 'i' where 'i' denotes that the element is the 'i'th smallest element, then an assignment will happen only if none of the n-i+1 larger elements apprar before the ith element in the array. The probability that this happens in a random array is 1/(n-i+1) for all i. Then we just apply linearity of expectations using an indicator random variable :)

like image 55
Banach Tarski Avatar answered Oct 23 '22 04:10

Banach Tarski