Pagini recente » Cod sursa (job #2147558) | Cod sursa (job #1687702) | Cod sursa (job #1342050) | Cod sursa (job #1136958) | Cod sursa (job #2773714)
#include <bits/stdc++.h>
using namespace std;
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
// Prefix Sums - O(N) space, O(N) time
int maxSubArray(vector<int>& arr, int n, int& pos1, int& pos2) {
pos1 = 0, pos2 = 0;
vector<int> pref(n);
for(int i = 0; i < n; ++i) {
pref[i] = arr[i] + (i == 0 ? 0 : pref[i - 1]);
}
int min_so_far = 0;
int answer = INT_MIN;
for(int j = 0; j < n; ++j) { //4*n bytes of space is required for the array a[] elements => O(N) space
// answer = max(answer, pref[j] - min_so_far);
if(answer < pref[j] - min_so_far) {
answer = pref[j] - min_so_far;
pos2 = j;
}
else {
if(min_so_far > pref[j])
pos1 = j + 1;
}
min_so_far = min(min_so_far, pref[j]);
}
return answer;
}
// // Kadane's Algorithm - O(1) space, O(N) time
// int Kadane(vector<int>& arr, int n, int& pos1, int& pos2) {
// pos1 = 0, pos2 = 0;
// long long ans = INT_MIN, a = 0;
// for(int x = 0; x < n; ++x) {
// a += arr[x];
// if(a >= ans) ans = a, pos2 = x;
// if(a < 0) // a = max(a, 0);
// a = 0, pos1 = x + 1;
// }
// return ans;
// }
int main() {
freopen("ssm.in", "r", stdin);
freopen("ssm.out", "w", stdout);
fast_cin();
int n, x, pos1, pos2;
vector<int> arr;
scanf("%d", &n);
// vector<int> arr {5, -6, 3, 4, -2, 3, -3};
for(int i = 0; i < n; ++i) {
scanf("%d", &x);
arr.push_back(x);
}
printf("%d ", maxSubArray(arr, n, pos1, pos2));
printf("%d %d", pos1 + 1, pos2 + 1);
return 0;
}