Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

algorithm - Number of assignments necessary to find the minimum value in an array?

Someone asked me a brainteaser, and I don't know; my knowledge slows down after amortized analysis, and in this case, this is O(n).

public int findMax(array) {
  int count = 0;
  int max = array[0];
  for (int i=0; i<array.length; i++) {
    if (array[i] > max) {
      count++;
      max = array[i];
    }
  } 
  return count;
}

What's the expected value of count for an array of size n?

Numbers are randomly picked from a uniform distribution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let f(n) be the average number of assignments.

Then if the last element is not the largest, f(n) = f(n-1).

If the last element is the largest, then f(n) = f(n-1) + 1.

Since the last number is largest with probability 1/n, and not the largest with probability (n-1)/n, we have:

f(n) = (n-1)/n*f(n-1) + 1/n*(f(n-1) + 1)

Expand and collect terms to get:

f(n) = f(n-1) + 1/n

And f(1) = 0. So:

f(1) = 0
f(2) = 0 + 1/2
f(3) = 0 + 1/2 + 1/3
f(4) = 0 + 1/2 + 1/3 + 1/4

That is, f(n) is the n_th "Harmonic number", which you can get in closed form only approximately. (Well, one less than the n_th Harmonic number. The problem would be prettier if you initialized max to INT_MIN and just let the loop run, so that f(1) = 1.)

The above is not a rigorous proof, since I was sloppy about expected values versus actual values. But I believe the answer is right anyway :-).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...