Optimal way to read a book having N chapters in M days

前端 未结 1 1264
感情败类
感情败类 2021-01-05 12:50

I came across this interview question: Given a book with N chapters (each chapter has of course different number of pages), what is the optimal way to complete the entire bo

1条回答
  •  孤城傲影
    2021-01-05 13:19

    You can use dynamic programming.

    1. The average is equal to totalNumberOfPages / numberOfDays and it does not depend on the way we read the book.

    2. The state is (number of chapters we have finished, the number of days we have already spent). The value of a state is the minimum sum of absolute differences so far.

    3. The base case if f(0, 0) = 0.

    4. Transitions are as follows:

      • Let's assume that the current state is (chapters, days).

      • We can iterate over the number of chapters we will read the next day(I will call it add) and make the following transition: f(chapters + add, days + 1) = min(f(chapters + add, days + 1), f(chapters, days) + abs(average - the number of pages in chapter + 1 ... chapter + add chapters).

    5. The answer is f(totalNumberOfChapters, totalNumberOfDays).

    This solution is based on an assumption that our goal is to "minimize the sum of absolute differences of total pages read with the average number of pages that one should 'ideally' read on one day".

    But if the problem statement does not say what the criterion of optimality is, I would suggest minimizing the maximum number of pages read during one day(in my opinion, the goal not too read to much in a row makes more sense). In this case, there is a more simple and efficient solution: we can binary search over the answer and use a greedy algorithm to check if a fixed candidate is feasible.

    0 讨论(0)
提交回复
热议问题