Cod sursa(job #2773653)

Utilizator andrei1985Gradisteanu Andrei andrei1985 Data 8 septembrie 2021 11:12:18
Problema Subsecventa de suma maxima Scor 75
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;

// // Prefix Sums - O(N) space, O(N) time
// int maxSubArray(vector<int>& arr) {

//     int n = arr.size();
//     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);
//         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;
    int 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);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    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);
    }
    cout << Kadane(arr, n, pos1, pos2) << " ";
    cout << pos1 + 1 << " " << pos2 + 1;


    return 0;
}