(UVA) The jackpot - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1625

The solution below used Kadane's algorithm, related to Dynamic Programming, to solve this problem.


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

class Main {
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        int numBets = sc.nextInt();
        while (numBets != 0) {
            int[] bets = new int[numBets];
            for (int i = 0; i < numBets; i++) {
                bets[i] = sc.nextInt();
            }   
           
            int[] sumBets = new int[numBets+1];
            sumBets[0] = 0;
            int max = 0;
            int totalMax = 0;
            for (int i = 1; i <= numBets; i++) {
                if (sumBets[i-1]+bets[i-1] > 0) {
                    sumBets[i] = sumBets[i-1]+bets[i-1];
                }
                else {
                    sumBets[i] = 0;
                }
                max = Math.max(max, sumBets[i]);
                totalMax = Math.max(max, totalMax);
            }
           
            if (totalMax == 0) {
                bw.write("Losing streak.\n");
            }
            else {
                bw.write("The maximum winning streak is " + totalMax + ".\n");
            }
           
            numBets = sc.nextInt();
        }
               
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        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