You are viewing a single comment's thread. Return to all comments →
O(n)
void maxSubarray(int n, const vector<int>& arr) { vector<int> subarray(n), subsequence(n); subarray[0] = arr[0]; subsequence[0] = arr[0]; for (int i=1; i < n; ++i) { subarray[i] = max(subarray[i-1] + arr[i], arr[i]); subsequence[i] = max( {subsequence[i-1], subsequence[i-1] + arr[i], arr[i]} ); } cout << *max_element(subarray.begin(), subarray.end()) << ' ' << subsequence[n-1] << '\n'; }
Seems like cookies are disabled on this browser, please enable them to open this website
The Maximum Subarray
You are viewing a single comment's thread. Return to all comments →
O(n)