aboutsummaryrefslogtreecommitdiff
path: root/picker.java
blob: 708273caaeb3f98f85d1700c7bb94754aa8df95d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;
import java.io.*;

public class Stock {
    int price, value;
    String ticker;

    public Stock() {
		price = 0;
		value = 0;
		ticker = "";
    }

    public Stock(int price, int value, String ticker) {
		this.price = price;
		this.value = value;
		this.ticker = ticker;
    }
}

public class Backpointer {
    static Stock NOTHING = new Stock(1, 0, "");

    int previousValue, totalValue;
    Stock stock;

    public Backpointer(int previousValue, Stock stock) {
		this.stock = stock;
		this.totalValue = previousValue + stock.value;
    }

	public static Backpointer chooseBackpointer(Stock stocks[],
		ArrayList<Backpointer> backpointers) {

		int currentPrice = backpointers.size();
		Backpointer best = 
		new Backpointer(backpointers.get(currentPrice - 1).totalValue, NOTHING);
		for (int i = 0; i < stocks.length; i++) {
    		Stock stock = stocks[i];	
	    	int previousPrice = currentPrice - stock.price;
	    	if (previousPrice >= 0) {
	    		Backpointer candidate = 
	    		new Backpointer(backpointers.get(previousPrice).totalValue, stock);
			    if (candidate.totalValue > best.totalValue) {
	    	    	best = candidate;
			    }
		    }
		}
		return best;
	}

	public static ArrayList chooseStocks(Stock stocks[], int priceLimit) {
		// assert stock values are integers
		
		// create backpointers
		ArrayList<Backpointer> backpointers = new ArrayList<Backpointer>();
		backpointers.add(new Backpointer(0, NOTHING));
		while (backpointers.size() <= priceLimit) {
			backpointers.add(chooseBackpointer(stocks, backpointers));
		}

		// postprocess backpointers
		ArrayList<Stock> result = new ArrayList<Stock>();
		for (int price = priceLimit; price > 0; 
		price -= backpointers.get(price).stock.price) {
			Stock stock = backpointers.get(price).stock;
			if (stock != NOTHING)
				result.add(stock);
			result.add(backpointers.get(price).stock);
		}
		Collections.reverse(result);

		return result;
	}

	public static void main(String[] args) {
		Stock stocks[] = {new Stock(3, 10, "A"), new Stock(4, 14, "B")};
		int priceLimit = 10;
		ArrayList result = chooseStocks(stocks, priceLimit);
	}
}