-1

There are N integers in an array.If you select element at index "i",then you get array[i] value in your packet, and array[i],array[i-1] and array[i+1] becomes zero, after selecting array[i] (i.e You can't take these elements any more in next selections). What is the maximum sum you can make in your packet by selecting array elements before all elements become zero ?

  • Please include what you've tried instead of just including a problem statement. If you need guidance on a specific aspect of the problem, please make that clear. Otherwise your question reads like a "do my work for me" request and is too broad. – ryanyuyu Aug 05 '15 at 16:43
  • I am sorry, by the way i asked..i tried it a lot. Let me give you the brief summary of what i thought for it. Firstly, i thought , lets use greedy approach, this way i will keep picking up the maximum element remaining in the array. But in several cases it is not giving the correct solution. Then , i thought of using DP,as the problem has optimal substructure and overlapping sub problems. But i am not able to form the recursive equation for the problem. Hence i need help in that part. Thanks :) – Nitish Kumar Aug 05 '15 at 17:00
  • @ryanyuyu should i explain more about my approach ?? – Nitish Kumar Aug 05 '15 at 17:22
  • Please [edit] that information into your post. Any past attempts really help. Include code if possible, even if it doesn't work. – ryanyuyu Aug 05 '15 at 18:06
  • Is it a requirement that the entire array is 0's at the end? If all integers are non-negative that won't matter but if negative elements are allowed it does. – Stef Aug 06 '15 at 13:15

1 Answers1

0

For each i we can either take that item or ignore it. We do the one which yields better result. Following is the dp approach:

const int N=10;
int a[]={1,2,3,4,5,6,7,8,9,10};
int dp[N];

int main() {
    dp[0]=a[0];
    dp[1]=max(a[0],a[1]);
    for(int i=2;i<N;i++) {
        dp[i]=max(dp[i-2]+a[i],dp[i-1]);  
        // dp[i-2]+a[i] is we include item i, hence we cannot take item i-1
        // dp[i-1] is we don't take item i
    }
    cout<<dp[N-1];
    return 0;
}
xashru
  • 3,400
  • 2
  • 17
  • 30