Skip to content

Instantly share code, notes, and snippets.

@seblm
Last active August 29, 2015 14:07
Show Gist options
  • Save seblm/1cadc9de66c079b155d9 to your computer and use it in GitHub Desktop.
Save seblm/1cadc9de66c079b155d9 to your computer and use it in GitHub Desktop.
katastrophic refactored
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Inv3st_Plan {
static final int MAX_HOURS = 12;
static String compute(String input) {
MaxProfits maxProfits = new MaxProfits();
Scanner scanner = new Scanner(input);
scanner.nextInt();
while (scanner.hasNext()) {
final int amount = scanner.nextInt();
final List<Integer> prices = new ArrayList<>();
for (int i = 1; i <= MAX_HOURS; i++) {
prices.add(scanner.nextInt());
}
maxProfits.computeCase(amount, prices);
}
return maxProfits.toString();
}
}
import static java.lang.String.format;
import static java.util.Optional.empty;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
class MaxProfits {
private final List<Optional<Profit>> caseResults;
MaxProfits() {
this.caseResults = new ArrayList<>();
}
void computeCase(int amount, List<Integer> prices) {
Optional<Profit> maxProfit = empty();
for (int buyIndex = 1; buyIndex <= prices.size(); buyIndex++) {
for (int sellIndex = buyIndex; sellIndex <= prices.size(); sellIndex++) {
Profit currentProfit = new Profit(amount, buyIndex, sellIndex, prices);
if (currentProfit.profit > maxProfit.map(profitResult -> profitResult.profit).orElse(0)) {
maxProfit = Optional.of(currentProfit);
}
}
}
caseResults.add(maxProfit);
}
@Override
public String toString() {
final StringJoiner output = new StringJoiner("\n");
int caseNumber = 1;
for (Optional<Profit> caseResult : caseResults) {
output.add(format("Case #%d: %s", caseNumber++, caseResult.map(Profit::toString).orElse("IMPOSSIBLE")));
}
return output.toString();
}
}
import java.util.List;
class Profit {
final int buyIndex;
final int sellIndex;
final int profit;
Profit(int amount, int buyIndex, int sellIndex, List<Integer> prices) {
this.buyIndex = buyIndex;
this.sellIndex = sellIndex;
int buyPrice = prices.get(buyIndex - 1);
int sellPrice = prices.get(sellIndex - 1);
int quantity = amount / buyPrice;
this.profit = quantity * sellPrice - quantity * buyPrice;
}
@Override
public String toString() {
return buyIndex + " " + sellIndex + " " + profit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment