We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I solve this with Java language. Normally, i saw everyone solve this problem with the idea to calculate the total value and at the end minus to the minimum possible value. This method can be done with O(n) to calculate sum, O(n* log(m)) to sort (m <= n) and then traverse it O(m) to minus as the followed idea.
Mine use heap as a quicker way (i believe) to solve this problem with only O(n* log(k)) time complexity and O(k) space complexity.
publicstaticintluckBalance(intk,List<List<Integer>>contests){// Write your code here//Count total and add to the heap, keep k element biggest.int[]heap=newint[k];intsize=0;//size <= kinttotal=0;intminus=0;for(inti=0;i<contests.size();i++){//O(n*log(k))inttemp=contests.get(i).get(0);total+=temp;if(contests.get(i).get(1)==1){//O(log(k))if(size<k){//O(log(k))heap[size]=temp;upHeap(heap,size++);//O(log(k))}elseif(size>0&&temp>heap[0]){//if(temp > heap[0] && size > 0) -> may return errorminus+=downHeap(heap,--size);//O(log(k))heap[size]=temp;upHeap(heap,size++);//O(log(k))}elseminus+=temp;//O(1)}}returntotal-minus*2;}privatestaticvoidupHeap(int[]heap,intlastIdx){//O(log(k))while(lastIdx>0&&heap[lastIdx]<heap[(lastIdx-1)/2]){swap(heap,lastIdx,(lastIdx-1)/2);lastIdx=(lastIdx-1)/2;}}privatestaticintdownHeap(int[]heap,intlastIdx){//O(log(k))inttemp=heap[0];heap[0]=heap[lastIdx];heap[lastIdx]=0;// size := lastIdxinti=0;while(2*i+2<lastIdx){if(heap[2*i+1]<heap[2*i+2]&&heap[i]>heap[2*i+1]){swap(heap,i,2*i+1);i=2*i+1;}elseif(heap[2*i+1]>=heap[2*i+2]&&heap[i]>heap[2*i+2]){swap(heap,i,2*i+2);i=2*i+2;}elsebreak;}if(2*i+1<lastIdx&&heap[2*i+1]<heap[i]){swap(heap,i,2*i+1);}returntemp;}privatestaticvoidswap(int[]heap,intidxA,intidxB){//O(1)inttemp=heap[idxA];heap[idxA]=heap[idxB];heap[idxB]=temp;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Luck Balance
You are viewing a single comment's thread. Return to all comments →
I solve this with Java language. Normally, i saw everyone solve this problem with the idea to calculate the total value and at the end minus to the minimum possible value. This method can be done with O(n) to calculate sum, O(n* log(m)) to sort (m <= n) and then traverse it O(m) to minus as the followed idea. Mine use heap as a quicker way (i believe) to solve this problem with only O(n* log(k)) time complexity and O(k) space complexity.