Algorithm to find maximum sum of elements in an array such that not more than k elements are adjacent

前端 未结 2 1391
长发绾君心
长发绾君心 2021-01-05 04:59

I came across this question. Given an array containing only positive values, you want to maximize the sum of chosen elements under the constraint that no group of more than

2条回答
  •  独厮守ぢ
    2021-01-05 05:39

    Your code is correct (at least the thought is correct), also, Up to now, I have not found any wrong test data. Follow your thought, we can list the DP equation

    P(v)=max{sum(C[v]~C[v+i-1])+P(v+i+1),0<=i<=k}

    In this equation, P(v) means the maximum in {C[v]~C[n]}(we let {C[1]~C[n]} be the whole list), so we just need to determine P(1).

    I have not find a better solution up to now, but your code can be optimized, after you determine P(v), you can save the data i, so when you find P(v-1), you can just compare sum(C[v-1]+C[v]~C[v+i-1])+P[v+i+1] with P[v+1]+C[v] when i!=k, the worst complexity is the same, but the best complexity is linear.

提交回复
热议问题