简体   繁体   中英

Algorithm - Minimum Greater Than Size

I have a problem with this:

We have an integer array (size n) [x_1,x_2,...,x_n]

We have to find the longest common part [x_i,x_i+1,...,x_j] that minimum of (x_i,x_i+1,...,x_j) >= j-i+1 fe [2,2,1,4,3,3,1] -> 3 (the longest correct part is 4,3,3 )

I can't figure out how to reduce time below O(n^2) (Checking every single segment) My second idea was: Every value x_k is equal to the "length range" that this part may have, if there is lower number then we change "length range" (in a meanwhile counting how long is this segment), but I don't have a clue what to do if we get greater numbers

(I would be really thankful for any help - there is probably another simpler solution, but I don't see it)

Caterpillar method, O(n), assuming all integers will be positive:

  • Put a left and right pointer on the first number, and your minimum = this number. Length = 1
  • Advance the right pointer by one, check for the condition (you know if there's a new minimum very easily, and you know the length += 1)
  • If you cannot advance the right pointer without breaking the condition, advance the left pointer and update your values
  • If you cannot advance the left pointer either, you have found a section satisfying the condition. Note its length, and start a new section in the same way, on the next index.

Example for you:

[2,2,1,4,3,3,1]
[2] <- The first 2
[2,2] <- Moved the right
[2] <- Moved the left, both R and L are pointing at the second 2
<-Can't move either, note max length and indices from previous run.
[1] <- Starting again
<-Can't move either
[4] <- Starting again
[4,3] <- Right
[4,3,3] <- Right (New max length and indices noted)
[3,3] <- Left. Doesn't improve the max
[3] <- Left again.
<- Can't move either, note max and indices, in this case overwrite length
[1] <-Start again
<- end of loop, check global max length, output

This is O(n) because each pointer (L and R) only moves over any given index once.

I think this should be enough for you to write the algorithm in any language you choose. Look out for the end-of-loop condition, because you have to check against the global max length if you run out of array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM