diff --git a/algorithms/dynamic_programming/maxsubarray/README.md b/algorithms/dynamic_programming/maxsubarray/README.md new file mode 100644 index 0000000..c3da2f0 --- /dev/null +++ b/algorithms/dynamic_programming/maxsubarray/README.md @@ -0,0 +1 @@ + diff --git a/algorithms/dynamic_programming/maxsubarray/solution.cpp b/algorithms/dynamic_programming/maxsubarray/solution.cpp new file mode 100644 index 0000000..944e36c --- /dev/null +++ b/algorithms/dynamic_programming/maxsubarray/solution.cpp @@ -0,0 +1,39 @@ +#include +#include + + +int main() +{ + using namespace std; + + size_t T; + cin >> T; + + while (T--) { + + size_t N; + cin >> N; + + int v; + cin >> v; + N--; + + long long max_sum_cont = v; + long long max_sum_cont_tmp = v; + long long max_sum_noncont = v; + + while (N--) { + + cin >> v; + + max_sum_cont_tmp = max((long long)v, max_sum_cont_tmp + v); + max_sum_cont = max(max_sum_cont, max_sum_cont_tmp); + + max_sum_noncont = max((long long)v, max_sum_noncont + (v > 0 ? v : 0)); + } + + cout << max_sum_cont << ' ' << max_sum_noncont << endl; + } + + return 0; +}