Last active
March 22, 2019 14:14
-
-
Save lnikon/41bbccf19b8b7fb9ab3d5afc2ec6f6bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
#include <iterator> | |
#include <utility> | |
template <class ForwardIterator, class Comp = std::less<>> | |
auto maxSum(ForwardIterator begin, | |
ForwardIterator end, | |
Comp comp = Comp()) { | |
using value_type = typename std::decay<decltype(*begin)>::type; | |
auto length = std::distance(begin, end); | |
auto sumVec = std::vector<value_type>{begin, end}; | |
for(auto firstBegin{begin}; firstBegin != end; ++firstBegin) { | |
auto fromBeginToFirstBegin = std::distance(begin, firstBegin); | |
for(auto secondBegin{begin}; secondBegin != firstBegin; ++secondBegin) { | |
auto fromBeginToSecondBegin = std::distance(begin, secondBegin); | |
auto newSum = sumVec[fromBeginToSecondBegin] + *firstBegin; | |
if( comp(*secondBegin, *firstBegin) && | |
comp(sumVec[fromBeginToFirstBegin], newSum)) { | |
sumVec[fromBeginToFirstBegin] = newSum; | |
} | |
} | |
} | |
return *std::max_element(std::begin(sumVec), std::end(sumVec)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment