Cod sursa(job #2436348)

Utilizator CiobaCatalinCioba Catalin Adrian CiobaCatalin Data 5 iulie 2019 15:43:02
Problema Subsecventa de suma maxima Scor 35
Compilator java Status done
Runda Arhiva educationala Marime 1.24 kb
import java.io.*;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        try (Scanner in = new Scanner(new File("ssm.in"));
                FileWriter fout = new FileWriter(new File("ssm.out"))) {
            int n = in.nextInt();

            int arr[] = new int[n];

            for (int i = 0; i < n; ++i) {
                arr[i] = in.nextInt();
            }

            int sumSoFar = arr[0];
            int minSoFar = arr[0];
            int minSoFarIdx = 0;
            
            int maxSubsequence = arr[0];
            int maxSubEnd = 0;
            int maxSubStart = 0;

            for (int i = 1; i < n; ++i) {
                sumSoFar += arr[i];

                if (sumSoFar < minSoFar) {
                    minSoFar = sumSoFar;
                    minSoFarIdx = i;
                }
                if (sumSoFar - minSoFar > maxSubsequence) {
                    maxSubsequence = sumSoFar - minSoFar;
                    maxSubEnd = i;
                    maxSubStart = minSoFarIdx + 1;
                }
            }
            fout.write(maxSubsequence + " " + 
            (maxSubStart + 1) + " " + (maxSubEnd + 1));

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}