Max Array Sum

  • + 0 comments

    very straightforward dynamic programming question, O(n)

    int maxSubsetSum(int n, const vector<int>& arr) {
        vector<int> cache(n);
        cache[0] = arr[0];
        cache[1] = max(arr[0], arr[1]);
        for (int i=2; i < n; ++i) cache[i] = max( {cache[i-1], cache[i-2] + arr[i], arr[i]} );
        return max(cache.back(), 0);
    }