You are given the stock prices for a set of days . Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing. What is the maximum profit you can obtain by planning your trading strategy optimally?
Examples ( The input i.e the no of days can vary )
5 3 2 => profit = 0 // since the price decreases each day ,the max profit we can make = 0
1 2 100 => profit = 197
1 3 1 2 =>profit = 3 // we buy at 1 sell at 3 , then we buy at 1 and sell at 2 ..total profit = 3
My solution sounds exactly like the answer given but for some reason my algorithm is not returning the correct answer for some large test cases . Can anybody see a problem with my code ?
public class StockMax {
private static final int BUY = 1;
private static final int SELL = 0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner stdin = new Scanner(System.in);
//int T;
//T = stdin.nextInt();
//while (T-- > 0) {
int N;
int[] price;
int[] opt;
N = stdin.nextInt();
price = new int[N];
opt = new int[N];
for (int i = 0; i < N; i++) {
price[i] = stdin.nextInt();
}
opt[N - 1] = SELL;
for (int i = N - 1; i > 0; i--) {
if (price[i - 1] < price[i]) {
opt[i - 1] = BUY;
} else {
opt[i - 1] = SELL;
}
}
int own, profit, cost;
own = profit = cost = 0;
for (int i = 0; i < N; i++) {
if (opt[i] == BUY) {
own++;
cost += price[i];
} else {
profit += ((own * price[i]) - cost);
cost = own = 0;
}
}
System.out.println(profit);
}
}
This is the updated version of my code as mentioned in my comments below. I still fail more test cases then pass.
import java.util.Scanner;
public class StockMax {
private static final int BUY = 1;
private static final int SELL = 0;
private static int glb_max;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner stdin = new Scanner(System.in);
int T;
T = stdin.nextInt();
while (T-- > 0) {
int N;
int[] price;
int[] opt;
N = stdin.nextInt();
price = new int[N];
opt = new int[N];
for (int i = 0; i < N; i++) {
price[i] = stdin.nextInt();
}
opt[N - 1] = SELL;
glb_max = price[N - 1];
for (int i = N - 1; i > 0; i--) {
if (price[i - 1] <= glb_max ) {
opt[i - 1] = BUY;
} else {
opt[i - 1] = SELL;
glb_max = price[i - 1];
}
}
/*
for(int i = 0; i < N;i++){
System.out.print(opt[i] + " ");
}
*/
int own, profit, cost;
own = profit = cost = 0;
for (int i = 0; i < N; i++) {
if (opt[i] == BUY) {
own++;
cost += price[i];
} else {
profit += ((own * price[i]) - cost);
cost = own = 0;
}
}
System.out.println(profit);
}
}
}