In non-decreasing sequence of (positive) integers two elements can be removed when . How many pairs can be removed at most from this sequence?
So I have thought of the following solution:
- I take given sequence and divide into two parts (first and second).
- Assign to each of them iterator - it_first := 0 and it_second := 0, respectively. count := 0
- when it_second != second.length
- if 2 * first[it_first] <= second[it_second]
- count++, it_first++, it_second++
- else
- it_second++
- if 2 * first[it_first] <= second[it_second]
- count is the answer
Example:
count := 0
[1,5,8,10,12,13,15,24] --> first := [1,5,8,10], second := [12,13,15,24]
2 * 1 ?< 12 --> true, count++, it_first++ and it_second++
2 * 5 ?< 13 --> true, count++, it_first++ and it_second++
2 * 8 ?< 15 --> false, it_second++
8 ?<24 --> true, count ++it_second reach the last element - END.
count == 3
Linear complexity (the worst case when there are no such elements to be removed. n/2 elements compare with n/2 elements). So my missing part is 'correctness' of algorithm - I've read about greedy algorithms proof - but mostly with trees and I cannot find analogy. Any help would be appreciated. Thanks!
EDIT: By correctness I mean: * It works * It cannot be done faster(in logn or constant)
I would like to put some graphics but due to reputation points < 10 - I can't.
(I've meant one latex at the beginning ;))
[1, 2, 4, 9]
.[4, 9]
could also be such pair. Or as in your example,[12, 24]
could also be such pair. – Arabela