-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (28 loc) · 752 Bytes
/
Copy pathsolution.cpp
File metadata and controls
36 lines (28 loc) · 752 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
class Solution
{
public:
int maxSubstring(string &s)
{
// Stores maximum difference found so far
int maxSum = -1;
// Stores current substring sum
int currentSum = 0;
for (char ch : s)
{
// Convert:
// '0' -> +1
// '1' -> -1
int value = (ch == '0') ? 1 : -1;
// Extend current substring
currentSum += value;
// Update best answer
maxSum = max(maxSum, currentSum);
// Negative sum can never help future substrings
if (currentSum < 0)
{
currentSum = 0;
}
}
return maxSum;
}
};