Skip to content

Commit

Permalink
leetcode #53 maximum subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
kpbochenek committed Dec 11, 2016
1 parent 61923b3 commit dd09549
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
2 changes: 2 additions & 0 deletions leetcode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
| 22 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) | Medium | [link](./generate_parentheses.cpp) |
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | Medium | [link](./search_insert_position.cpp) |
| 46 | [Permutations](https://leetcode.com/problems/permutations/) | Medium | [link](./permutations.cpp) |
| 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | Medium | [link](./maximum_subarray.cpp) |
| | | | |



50 changes: 50 additions & 0 deletions leetcode/maximum_subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Author: Krzysztof Bochenek
// Email: kpbochenek@gmail.com
// --------------------------------
#include <stdio.h>
#include <vector>
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <set>
#include <stack>
#include <math.h>
#include <algorithm>
#include <string>
#include <iostream>

// ---------------------

typedef long long int ll;
typedef unsigned long long ull;

using namespace std;

// ---------------------

template<class T>
void print_vec(const vector<T> &v, string desc = "") {
cout << desc << " ";
for (T e: v) {
cout << e << " ";
}
cout << endl;
}

// ---------------------

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int bestMax = 0;
int ptMax = nums[0];
int currentMax = 0;

for (int n: nums) {
currentMax = max(currentMax + n, 0);
bestMax = max(bestMax, currentMax);
ptMax = max(ptMax, n);
}
return bestMax == 0 ? ptMax : bestMax;
}
};

0 comments on commit dd09549

Please sign in to comment.