(SPOJ) Progressões aritméticas - Solution

Link to the problem: http://br.spoj.com/problems/PAS11/

The solution below checks every element from the left to the right to see if this element belongs to the current arithmetic progression.


import java.io.*;
import java.util.*;

class solucao {
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        String line = br.readLine();
        int numNumbers = Integer.parseInt(line);
       
        int numParts = 1;
        int lastDiff = 0;
        int comparison = 0;
        line = br.readLine();
        String[] s = line.split(" ");
        int lastNumber = Integer.parseInt(s[0]);
        for (int i = 1; i < numNumbers; i++) {
            int diff = Integer.parseInt(s[i])-lastNumber;
            if (comparison > 0 && diff != lastDiff) {
                numParts++;
                lastDiff = 0;
                comparison = 0;
                lastNumber = Integer.parseInt(s[i]);
                continue;
            }
            lastDiff = diff;
            comparison++;
            lastNumber = Integer.parseInt(s[i]);
        }
       
        bw.write(numParts+"\n");
           
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        solucao m = new solucao();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução