Skip to content

Commit f7bb47d

Browse files
committed
Runtime: 23 ms (Top 76.54%) | Memory: 23.70 MB (Top 72.35%)
1 parent f18c511 commit f7bb47d

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,23 @@
1+
// Runtime: 23 ms (Top 76.54%) | Memory: 23.70 MB (Top 72.35%)
2+
13
class Solution {
24
public:
3-
int maximumSum(vector<int>& arr) {
4-
int n = arr.size(), curr, maxi = INT_MIN;
5-
vector<int> fw(n + 1, 0), bw(n + 1, 0);
6-
fw[0] = arr[0];
7-
maxi = max(maxi, fw[0]);
5+
int maximumSum(vector<int>& a) {
86

9-
// ith element denotes the maximum subarray sum with ith element as the last element
10-
for(int i = 1; i < n; ++i) {
11-
curr = max(arr[i], fw[i - 1] + arr[i]);
12-
maxi = max(maxi, curr);
13-
fw[i] = curr;
14-
}
15-
16-
// similar to fw array, but in the backward direction
17-
bw[n - 1] = curr = arr[n - 1];
18-
for(int i = n - 2; i >= 0; --i) {
19-
curr = max(arr[i], bw[i + 1] + arr[i]);
20-
maxi = max(maxi, curr);
21-
bw[i] = curr;
22-
}
7+
// Kadane's Algo
8+
// DP time: O(N) space: O(N)
9+
// dp[i][2]-->dp[i][0]->suf_del and dp[i][1]->suf_no_del
2310

24-
int res = INT_MIN;
25-
for(int i = 1; i < n - 1; ++i) {
26-
res = max(res, fw[i - 1] + bw[i + 1]);
11+
// Space optimized time: O(N) space: O(1)
12+
int n=a.size();
13+
int suf_del=0;
14+
int suf_no_del=a[0];
15+
int ans=a[0];
16+
for(int i=1;i<n;i++){
17+
suf_del=max(suf_del+a[i],suf_no_del); // suf_del
18+
suf_no_del=max(suf_no_del+a[i],a[i]); // suf_no_del
19+
ans=max({ans,suf_del,suf_no_del});
2720
}
28-
return max(res, maxi);
21+
return ans;
2922
}
30-
};
23+
};

0 commit comments

Comments
 (0)