An algorithm for the maximum sum such that two elements are not adjacent:
Loop for all elements in arr [] and maintain two sums, including excl, where incl = the maximum amount, including the previous element, and excl = the maximum amount, excluding the previous element.
The maximum amount excluding the current element will be max (including, excluding), and the maximum amount including the current element will be the excl + current element (note that only excl is considered, because the elements cannot be adjacent).
At the end of the cycle, return max on. and not.
Implementation:
#include<stdio.h> /*Function to return max sum such that no two elements are adjacent */ int FindMaxSum(int arr[], int n) { int incl = arr[0]; int excl = 0; int excl_new; int i; for (i = 1; i < n; i++) { /* current max excluding i */ excl_new = (incl > excl)? incl: excl; /* current max including i */ incl = excl + arr[i]; excl = excl_new; } /* return max of incl and excl */ return ((incl > excl)? incl : excl); } /* Driver program to test above function */ int main() { int arr[] = {5, 5, 10, 100, 10, 5}; printf("%d \n", FindMaxSum(arr, 6)); getchar(); return 0; }
Difficulty of time: O (n)
Cosmic complexity: O (1)
Change 1:
If you understand the code above, we can easily cope with this problem by saving the number of adjacent numbers for the previous position. Here is a working implementation on a given question
//We could assume we store optimal result upto i in array sum //but we need only sum[i-3] to sum[i-1] to calculate sum[i] //so in this code, I have instead maintained 3 ints //So that space complexity to O(1) remains #include<stdio.h> int max(int a,int b) { if(a>b) return 1; else return 0; } /*Function to return max sum such that no three elements are adjacent */ int FindMaxSum(int arr[], int n) { int a1 = arr[0]+arr[1];//equivalent to sum[i-1] int a2 =arr[0];//equivalent to sum[i-2] int a3 = 0;//equivalent to sum [i-3] int count=2; int crr = 0;//current maximum, equivalent to sum[i] int i; int temp; for (i = 2; i < n; i++) { if(count==2)//two elements were consecutive for sum[i-1] { temp=max(a2+arr[i],a1); if(temp==1) { crr= a2+arr[i]; count = 1; } else { crr=a1; count = 0; } //below is the case if we sould have rejected arr[i-2] // to include arr[i-1],arr[i] if(crr<(a3+arr[i-1]+arr[i])) { count=2; crr=a3+arr[i-1]+arr[i]; } } else//case when we have count<2, obviously add the number { crr=a1+arr[i]; count++; } a3=a2; a2=a1; a1=crr; } return crr; } /* Driver program to test above function */ int main() { int arr[] = {2, 5, 3, 7, 8, 1}; printf("%d \n", FindMaxSum(arr, 6)); return 0; }
Difficulty of time: O (n)
Cosmic complexity: O (1)