Cod sursa(job #2420118)

Utilizator DogaruMihaiDogaru Mihai - Sorin DogaruMihai Data 10 mai 2019 17:35:31
Problema Subsecventa de suma maxima Scor 30
Compilator java Status done
Runda Arhiva educationala Marime 2.65 kb
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    static class Task {
        public final static String INPUT_FILE = "ssm.in";
        public final static String OUTPUT_FILE = "ssm.out";

        int n;
        int[] numere;

        private void readInput() {
            try {
                Scanner sc = new Scanner(new File(INPUT_FILE));
                n = sc.nextInt();
                numere = new int[n + 1];
                numere[0] = 0;
                for (int i = 1; i <= n; i++) {
                    numere[i] = sc.nextInt();
                }
                sc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private void writeOutput(int[] result) {
            try {
                PrintWriter pw = new PrintWriter(new File(OUTPUT_FILE));
                for (int rez : result) {
                    pw.printf("%d ", rez);
                }

                pw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private int[] getResult() {
            // TODO: Aflati punctajul maxim pe care il puteti obtine
            // planificand optim temele.
            int[] rezFinal = new int[3];
            //in rezFinal[0] am suma maxima
            //in 1 si 2 am indicii de start si final
            int[] dp = new int[n + 1];
            dp[1] = numere[1];

            for (int i = 2; i <= n; i++) {
                if (dp[i - 1] >= 0) {
                    dp[i] = dp[i - 1] + numere[i];
                } else {
                    dp[i] = numere[i];
                }
            }
            int max = Integer.MIN_VALUE;
            int indiceMax = -1;

            for (int i = 1; i <= n; i++) {
                if (max < dp[i]) {
                    max = dp[i];
                    indiceMax = i;
                }
            }
            int indiceFinal = indiceMax;
            int indiceStart;
            while (dp[indiceMax] > 0 && (indiceMax - 1) > 0) {
                indiceMax -= 1;
            }
            //trebuie adaugat 1 inapoi
            indiceMax += 1;

            indiceStart = indiceMax;
            rezFinal[0] = max;
            rezFinal[1] = indiceStart;
            rezFinal[2] = indiceFinal;

            return rezFinal;
        }

        public void solve() {
            readInput();
            writeOutput(getResult());
        }
    }

    public static void main(String[] args) {
        new Task().solve();
    }
}