Skip to content

Instantly share code, notes, and snippets.

@Dessix
Created October 7, 2016 04:22
Show Gist options
  • Save Dessix/5d615b42b634af89c00c79e730af0cc3 to your computer and use it in GitHub Desktop.
Save Dessix/5d615b42b634af89c00c79e730af0cc3 to your computer and use it in GitHub Desktop.
Max Summed Subarray Problem in O(N), C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <memory>
using namespace std;
typedef unsigned int uint;
struct BiContigRet {
const int contig, apb;
const uint start, length;
};
const BiContigRet maxBiContig(const vector<int> vals) {
int apb = 0, maxSeen = 0;
uint startIdx = 0, len = 0;
const uint n = vals.size();
if (n > 0) {
apb = maxSeen = vals[0];
startIdx = 0, len = 1;
int thisStart = 0, currentMax = vals[0];
for (int i=1;i<n;++i) {
const auto v = vals[i];
if (apb >= 0 && v > 0) { apb += v; } else if (v > apb) { apb = v; }
currentMax = currentMax >= 0 ? currentMax + v : (thisStart = i, v);
if (currentMax > maxSeen) {
maxSeen = currentMax;
len = 1 + i - (startIdx = thisStart);
}
}
}
return {maxSeen, apb, startIdx, len};
}
int cint() { int v; return cin >> v, v; }
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
const uint nc = cint();
auto* cases = new vector<int>*[nc];
for(auto i=0;i<nc;++i){
auto* c = cases[i] = new vector<int>();
for(auto x=0,clen=cint();x<clen;++x){
c->push_back(cint());
}
}
for (int i=0;i<nc;++i) {
const auto& r = maxBiContig(*unique_ptr<vector<int>>(cases[i]));
printf("%d %d\n", r.contig, r.apb);
//printf("Max was at %d with length %d\n", r.start, r.length);
}
flush(cout);
delete[] cases;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment