Skip to content

Instantly share code, notes, and snippets.

@songouyang
Created November 18, 2017 07:50
Show Gist options
  • Save songouyang/76db744332889313b9ecaeaeae9150c5 to your computer and use it in GitHub Desktop.
Save songouyang/76db744332889313b9ecaeaeae9150c5 to your computer and use it in GitHub Desktop.
53. Maximum Subarray
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int local_max = nums[0];
int global_max = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
local_max = max(nums[i], nums[i] + local_max);
global_max = max(local_max, global_max);
}
return global_max;
}
};
int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
Solution s;
cout << s.maxSubArray(nums) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment