Thursday, July 27th

 Keep all computers powered

Given a number of computers, and batteries of various sizes, where batteries can be freely swapped between computers, how long can we keep all computers simultaneously powered?


There are a couple of solutions to this problem.  Here we will use binary search, building off its use these past 2 days.

Similar to yesterday, binary search can be used while testing a target solution t.  In this case, given a collection of batteries, can we keep all the computers running for t minutes?  

To determine so, we iterate over all the batteries and sum up the available power e:

  • if a given battery length is greater than t, then we add only t to the available power, because the battery won't be available after t
  • Otherwise, if a battery is smaller than t, we add all its capacity to available power

    long e=0;
for(long b : batteries) {
    e+=min(t,b);
}

This capacity can be tested to see if it can power the batteries for the target time by multiplying the target time  t by n the number of computers.  If so, we set the left hand side of the binary search window to t, otherwise set.t-1 to the right side

    if( e>= (long)n*t) {
    l=t;
} else {
r=t-1;
}

Putting this all together, we start with original indices with left equal to 1, and right equal to the sum of all power divided by the number of computers, representing a perfect distribution

    long s = 0;
for(auto b : batteries) {
s += b;
}
long l=1, r=s/n;

Full implementation below:

    long long maxRunTime(int n, vector<int>& batteries) {
long s = 0;
for(auto b : batteries) {
s += b;
}
long l=1, r=s/n;
long t, e;
while(l<r) {
t= r-(r-l)/2;
long e=0;
for(long b : batteries) {
e+=min(t,b);
}
if( e>= (long)n*t) {
l=t;
} else {
r=t-1;
}
}
return l;
}

The solution here demonstrates some tricky details in binary search implementations.  Here is a blog entry about the details of binary search, and a paper off of arXiv discussing the same issues.

Shout out to the Editorial for helpful intuition

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th