Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

$T = \{t_1,t_2,\dots,t_n\} $. while $t_1,\dots,t_n \in \mathbb N$ with $t_i < t_j$ for $i < j$.

For each $t_1,\dots,t_n$, there is another value - Price. for example, for $t_1$, the price is 200.

Let $M$ be a natural number.

I have to find an Iterative algorithm which fullfil: $t_{j+1}-t_j\leq M$ for each j, and the sum of the prices in this group is MAX.

The problem is to find algorithm in $O(n)$. I think to use recursion formula for each $j$, by finding the MAX $t_i$ which fulfills $t_i+m<t_j$, but it requires $O(n(\log(n))$.

Any idea please? Thank u!

share|cite|improve this question
This is simple DP. – Yuval Filmus Mar 25 '11 at 13:22
I know. The problem is not with DP. I found DP algorithm with O(n(log(n)). I have difficult to find it in O(n). – Amir Mar 25 '11 at 13:29
up vote 1 down vote accepted

You can find for each $i$ the maximal $j$ such that $t_j \leq t_i + M$ in linear time by using a two-pointer approach.

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.