Skip to content

Instantly share code, notes, and snippets.

@laymonage
Last active June 19, 2020 09:15
Show Gist options
  • Save laymonage/547fd25ca740a3927bea9923bae5fac4 to your computer and use it in GitHub Desktop.
Save laymonage/547fd25ca740a3927bea9923bae5fac4 to your computer and use it in GitHub Desktop.
Pintu Engineering Logic Test #1

Jacky is a beginner trader, he wants to make a profit in trading cryptocurrency. But since he is a beginner, he plans to buy once and sell once.

Before he jumps into the real market, he want to analyze previous historical prices to know how much he can profit based on historical prices.

Example 1:
Price of bitcoin each hour
Hour 1: $5
Hour 2: $4
Hour 3: $3
Hour 4: $2
Hour 5: $1

In this scenario, the maximum profit Jacky can make is: 0

Example 2:
Price of bitcoin each hour
Hour 1: $3
Hour 2: $2
Hour 3: $1
Hour 4: $5
Hour 5: $6
Hour 6: $2

In this scenario, the maximum profit Jacky can make is: $5, he will buy at 3rd hour and sell at 5th hour.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
public class MaximumTrader {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] pricesStr = br.readLine().split(" ");
int[] prices = Arrays.stream(pricesStr).mapToInt(Integer::parseInt).toArray();
solve(prices);
}
public static int solve(int[] prices) {
int profit = 0;
int buy_idx = 0;
int sell_idx = 0;
int low_idx = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] - prices[low_idx] > profit) {
// The current price gives us larger profit
// given the previously smallest buying price.
buy_idx = low_idx;
sell_idx = i;
profit = prices[i] - prices[buy_idx];
}
if (prices[i] < prices[low_idx]) {
// Keep track of the smallest price.
low_idx = i;
}
}
System.out.printf("Maximum profit: %d%n", profit);
System.out.printf("Buy hour: %d (price: %d)%n", buy_idx + 1, prices[buy_idx]);
System.out.printf("Sell hour: %d (price: %d)%n", sell_idx + 1, prices[sell_idx]);
return profit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment