// Author: Marek K.
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Dieses Programm ist Freie Software: Sie koennen es unter den Bedingungen
der GNU General Public License, wie von der Free Software Foundation,
Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren
veroeffentlichten Version, weiter verteilen und/oder modifizieren.
Dieses Programm wird in der Hoffnung bereitgestellt, dass es nuetzlich sein wird, jedoch
OHNE JEDE GEWAEHR,; sogar ohne die implizite
Gewaehr der MARKTFAEHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
Siehe die GNU General Public License fuer weitere Einzelheiten.
Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
Programm erhalten haben. Wenn nicht, siehe .
*/
// Challenge from https://www.cprogramming.com/challenges/array_sum.html, retrieved on 24.06.2019
#include
#include
#include
#include
#include
using namespace std;
int main()
{
try
{
vector vec, subary, vres;
long sum, lres = 0, lsum;
cout << "Vector(exit with 1234): ";
cin >> sum;
if(cin.fail())
throw runtime_error("Invalid input!");
while(sum != 1234)
{
vec.push_back(sum);
cin >> sum;
if(cin.fail())
throw runtime_error("Invalid input!");
}
sum = 0;
for(vector::iterator it = vec.begin(); it < vec.end(); it++)
{
lsum = sum,
sum += *it;
if(lsum >= sum)
{
sum = lsum;
if(sum > lres)
lres = sum,
vres = subary;
subary.clear(),
sum = 0,
lsum = 0;
}
else
subary.push_back(*it);
}
if(sum >= lres)
{
lres = sum,
vres = subary;
}
if(vres.empty())
cout << "No largest subarray could be found." << endl;
else
{
for(vector::iterator it = vres.begin(); it < vres.end(); it++)
cout << *it << (it+1==vres.end()?"":" + ");
cout << " = " << lres << endl;
}
}
catch (const exception & e)
{
cerr << "Error: " << e.what() << endl;
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}