Skip to content

Commit 14a83dc

Browse files
MeetThakurpascalecu
authored andcommitted
Add Maximum Subarray in C++ (TheRenegadeCoder#5092)
1 parent 3b0d66e commit 14a83dc

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <iostream>
2+
#include <sstream>
3+
#include <vector>
4+
#include <limits>
5+
#include <string>
6+
7+
void print_usage()
8+
{
9+
std::cout << "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"\n";
10+
}
11+
12+
int max_subarray_sum(const std::vector<int> &arr)
13+
{
14+
int max_so_far = std::numeric_limits<int>::min();
15+
int max_ending_here = 0;
16+
17+
for (int num : arr)
18+
{
19+
max_ending_here += num;
20+
21+
if (max_so_far < max_ending_here)
22+
{
23+
max_so_far = max_ending_here;
24+
}
25+
26+
if (max_ending_here < 0)
27+
{
28+
max_ending_here = 0;
29+
}
30+
}
31+
32+
return max_so_far;
33+
}
34+
35+
int main(int argc, char *argv[])
36+
{
37+
if (argc < 2 || std::string(argv[1]).empty())
38+
{
39+
print_usage();
40+
return 1;
41+
}
42+
43+
// Parse input string
44+
std::vector<int> arr;
45+
std::string input = argv[1];
46+
std::stringstream ss(input);
47+
std::string token;
48+
49+
while (std::getline(ss, token, ','))
50+
{
51+
arr.push_back(std::stoi(token));
52+
}
53+
54+
// If less than two integers were provided
55+
if (arr.size() == 1)
56+
{
57+
std::cout << arr[0] << "\n";
58+
return 0;
59+
}
60+
else if (arr.empty())
61+
{
62+
print_usage();
63+
return 1;
64+
}
65+
66+
// Calculate maximum subarray sum
67+
int result = max_subarray_sum(arr);
68+
69+
std::cout << result << "\n";
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)