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.
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started