Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 4, 2020 03:47
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 bhaveshmunot1/7a466c6debdc944bee8b1e7550aaaa42 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/7a466c6debdc944bee8b1e7550aaaa42 to your computer and use it in GitHub Desktop.
Leetcode #53: Maximum Subarray
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
if (n==0) {
return 0;
}
vector<int> dp(n);
dp[0] = nums[0];
for (int i=1; i<n; i++) {
dp[i] = nums[i] + max(0, dp[i-1]);
}
return *max_element(dp.begin(), dp.end()); // max in the dp vector.
}
};
// You can easily reduce the space complexity by using 1-2 variables instead of an entire vector/array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment