Problem: Find the maximum sum in an array such that no two elements are adjacent.
Solution:
Maintain two sums for each element of the given array:
At the end max of the sum1 and sum2 will be our resultant value.
Implementation:
int maxSumWithoutAdjacentElem(int *arr, int len)
{
if(arr == NULL || len == 0)
return -1; //Error value
int sumIncludingCurr = arr[0], sumExcludingCurr = 0;
for(int i = 1; i < len; ++i)
{
int tempExcludingSum = max(sumIncludingCurr, sumExcludingCurr);
sumIncludingCurr = sumExcludingCurr + arr[i];
sumExcludingCurr = tempExcludingSum;
}
return max(sumIncludingCurr, sumExcludingCurr);
}
Complexity: O(n)
Solution:
Maintain two sums for each element of the given array:
- sum1 = Max sum including the previous element
- sum2 = Max sum excluding the previous element
Now:
- Max sum excluding the current element = max(sum1, sum2)
- Max sum including the current element = arr[i] + sum2
Implementation:
int maxSumWithoutAdjacentElem(int *arr, int len)
{
if(arr == NULL || len == 0)
return -1; //Error value
int sumIncludingCurr = arr[0], sumExcludingCurr = 0;
for(int i = 1; i < len; ++i)
{
int tempExcludingSum = max(sumIncludingCurr, sumExcludingCurr);
sumIncludingCurr = sumExcludingCurr + arr[i];
sumExcludingCurr = tempExcludingSum;
}
return max(sumIncludingCurr, sumExcludingCurr);
}
Complexity: O(n)
No comments:
Post a Comment