Skip to content

Instantly share code, notes, and snippets.

@dsapandora
Created April 6, 2020 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsapandora/2dbac55b83df882882d7e72b234597e0 to your computer and use it in GitHub Desktop.
Save dsapandora/2dbac55b83df882882d7e72b234597e0 to your computer and use it in GitHub Desktop.
Maximum sum such that no two elements are adjacent
#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};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d n", FindMaxSum(arr, n));
return 0;
}
# Function to return max sum such that
# no two elements are adjacent
def find_max_sum(arr):
incl = 0
excl = 0
for i in arr:
# Current max excluding i (No ternary in
# Python)
new_excl = excl if excl>incl else incl
# Current max including i
incl = excl + i
excl = new_excl
# return max of incl and excl
return (excl if excl>incl else incl)
# Driver program to test above function
arr = [5, 5, 10, 100, 10, 5]
print find_max_sum(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment