Question: Given the prices for a stock on n consecutive days, determine the largest profit which can be made by choosing a day on which to
Given the prices for a stock on n consecutive days, determine the largest profit which can be made by choosing a day on which to purchase the stock, and a subsequent day on which to sell the stock. Implement the following method in JAVA using dynamic programing with the given recurrence :
profit(i)=max{profit(i?1)+price(i)?price(i?1)0?
profit(0)=0
where profit(i) stands for the maximum profit attainable from selling on day i.
The Code:
import java.util.Arrays;
import java.util.Scanner;
import java.io.InputStream;
public class BuyLowSellHigh {
public static int computeMaxProfit(int[] prices) {
//TODO: METHOD TO IMPLEMEMNT.
return 0;
}
public static void main(String[] args) {
System.out.println(computeMaxProfit(loadPrices(System.in)));
}
public static int[] loadPrices(InputStream stream) {
final int DEFAULT_CAPACITY = 10;
int[] prices = new int[DEFAULT_CAPACITY];
int index = 0;
Scanner scanner = new Scanner(stream);
while (scanner.hasNext()) {
if (index == prices.length) {
prices = Arrays.copyOf(prices, prices.length*2);
}
prices[index] = scanner.nextInt();
index++;
}
return Arrays.copyOf(prices, index);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
