Блог пользователя ladpro98

Автор ladpro98, 12 лет назад, По-английски

Here is the problem statement:

Given an array A[1..n]. Find the sub-array that it's sum is smallest and at least M. (all numbers in the input is 32bit integer)

Till now I cannot find a good solution. Can anyone help me with an O(n) or O(NlogN) algorithm?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
12 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Umm... pre-compute the partial sums in O(N) and bin-search in per query?

  • »
    »
    12 лет назад, скрыть # ^ |
    Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    Can you give me more details. I try to sort the SUM array but then I am unable to Bin-Search since the positions has changed.

    • »
      »
      »
      12 лет назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      What? Why would you sort? That'd obviously completely mess up the results. Also, what are "positions"?

      Compute prefix sums (or partial sums as you call it): S[i] = S[i - 1] + A[i], S[0] = 0.

      Ok, I just realized that A[i] can be negative, so bin-search won't work (it requires the sums to be increasing/decreasing). But you can still try all S[i] and pick the one that fits your condition. There are just O(N) of them, so the time complexity is O(N).