-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathMaximum_Subarray.cpp
More file actions
39 lines (35 loc) · 823 Bytes
/
Maximum_Subarray.cpp
File metadata and controls
39 lines (35 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 5, 2012
Problem: Maximum Subarray
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Solution:
DP.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
int maxSubArray(int A[], int n) {
int result = A[0];
int sum = A[0];
for (int i = 1; i < n; i++) {
sum= max(A[i], sum + A[i]);
result = max(sum, result);
}
return result;
}
};