UVA 10114 – Loansome Car Buyer

This problem was truly annoying and yet extremely simple at the same time. This has been ever so rightly starred in Competitive Programming 3 book. I messed up with an edge case and I wrote `break` instead of `continue` (big oops) in one of my many submissions. The problem mentions that we need to use files as input and output but that is not the case! That lost me a couple of tries as well :[

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 
 * @author Sanchit M. Bhatnagar
 * @see http://uhunt.felix-halim.net/id/74004
 * 
 */
public class P10114 {

	public static void main(String[] args) throws FileNotFoundException {
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		while (true) {
			int duration = sc.nextInt();
			double downpayment = sc.nextDouble();
			double loan = sc.nextDouble();
			int depreciations = sc.nextInt();
			if (duration < 0) {
				break;
			}
			double valOfCar = loan + downpayment;
			double monthlyPayment = loan / duration;

			int[] depList = new int[depreciations];
			double[] depVal = new double[depreciations];
			for (int i = 0; i < depreciations; i++) {
				depList[i] = sc.nextInt();
				depVal[i] = sc.nextDouble();
			}

			int lastMonth = 0;
			double lastVal = depVal[0];

			valOfCar *= (1 - lastVal);

			if (loan < valOfCar) {
				out.println("0 months");
				continue;
			}

			lastMonth = 1;

			for (int i = 1; i < depList.length; i++) {
				int nextMonth = depList[i];
				double nextMonthDepreciation = depVal[i];
				while (lastMonth <= nextMonth) {
					if (nextMonth == lastMonth) {
						lastVal = nextMonthDepreciation;
					}
					valOfCar *= (1 - lastVal);
					loan -= monthlyPayment;
					lastMonth++;
					if (loan < valOfCar) {
						break;
					}
				}
				if (loan < valOfCar) {
					break;
				}
			}
			while (loan > valOfCar) {
				valOfCar *= (1 - lastVal);
				loan -= monthlyPayment;
				lastMonth++;
			}

			lastMonth--;
			if (lastMonth == 1) {
				out.println("1 month");
			} else {
				out.println(lastMonth + " months");
			}
		}
		out.close();
		sc.close();
	}

}

2 thoughts on “UVA 10114 – Loansome Car Buyer”

  1. Hey, thanks for your comment.

    Yes, Scanner is indeed very very slow. I actually change the type of input reading I do depending on the type of problem. If the problem lets me be lazy then I use the Scanner class’ built in (more convenient) methods. Otherwise I use a BufferedReader. :)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.