data-structures · intermediate · ~15 min
Maximize a non-adjacent sum along a line.
Implement:
long long rob_linear(const int *a, int n);
Return the maximum sum of elements of a[0..n-1] (non-negative) such that no two chosen elements are adjacent.
Non-negative a, count n.
Maximum non-adjacent sum.
O(1) extra space suffices.
#include <stddef.h>
/* Maximum sum of non-adjacent elements of a[0..n-1] (non-negative). */
long long rob_linear(const int *a,int n){ (void)a;(void)n; return 0; }
Only considering 'take every other' — the optimum can skip two in a row.
Empty -> 0; single -> that value.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.