(UVA) Maximum Product - Solution

Brute Force was used to solve this problem.


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

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        int numCase = 0;
        String line = br.readLine();
        while (line != null) {
            int numElements = Integer.parseInt(line);
            int[] elements = new int[numElements];
            line = br.readLine();
            String[] s = line.split("\\s");
            for (int i = 0; i < numElements; i++) {
                elements[i] = Integer.parseInt(s[i]);
            }

            long biggestProduct = -1;
            for (int i = 0; i < numElements; i++) {
                long product = elements[i];
                if (product > biggestProduct) {
                    biggestProduct = product;
                }
                for (int j = i+1; j < numElements; j++) {
                    product *= elements[j];
                    if (product > biggestProduct) {
                        biggestProduct = product;
                    }
                }
            }
           
            if (biggestProduct < 0) {
                System.out.println("Case #" + ++numCase + ": The maximum product is 0.\n");
            }
            else {
                System.out.println("Case #" + ++numCase + ": The maximum product is " + biggestProduct + ".\n");
            }
                   
            line = br.readLine();
            if (line != null && line.equals("")) {
                line = br.readLine();
            }
        }

        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