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

前端 未结 2 1390
长发绾君心
长发绾君心 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.

    0 讨论(0)
  • 2021-01-05 05:43

    I think this will work :

    findMaxSum(int a[], int in, int last, int k) { // in is current index, last is index of last chosen element
        if ( in == size of a[] ) return 0;
        dontChoseCurrent = findMaxSum(a, in+1, last, k); // If current element is negative, this will give better result
        if (last == in-1 and k > 0) { // last and in are adjacent, to chose this k must be greater than 0
            choseCurrentAdjacent = findMaxSum(a, in+1, in, k-1) + a[in];
        }
        if (last != in-1) { // last and in are not adjacent, you can chose this.
            choseCurrentNotAdjacent = findMaxSum(a, in+1, in, k) + a[in];
        }
        return max of dontChoseCurrent, choseCurrentAdjacent, choseCurrentNotAdjacent
    }
    
    0 讨论(0)
提交回复
热议问题