Created
June 4, 2020 03:47
-
-
Save bhaveshmunot1/7a466c6debdc944bee8b1e7550aaaa42 to your computer and use it in GitHub Desktop.
Leetcode #53: Maximum Subarray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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