Buy and Sell Stock Only Multiple Times to Maximize Profit
package org.wesome.dsalgo;
import lombok.Data;
import java.util.ArrayList;
import java.util.stream.IntStream;
@Data
class Trading {
int buy, sell;
}
class StockBuySell {
static void stockBuySell(int trade[]) {
// in order to buy and sell, trades must happen for at least two days
if (trade.length < 2) {
System.out.println("trading is required for at lest 2 days, but provided for " + trade.length + " days only.");
return;
}
ArrayList<Trading> tradeDays = new ArrayList<>();
int day = 0;
while (day < trade.length - 1) {
// assuming stock buy on day 1 then price must go up in order to sell, there must be altest 1 day where price must be lower then buy
// find the day when today price is greater than tomorrow price
while ((day < trade.length - 1) && (trade[day] >= trade[day + 1])) {
day++;
}
// if no day is find, then cannot sell to make profit
if (day == trade.length - 1) {
break;
}
// we have reached here means there is altest 1 day where sell price is greater then buy price
Trading e = new Trading();
e.buy = day;
day++;
// Store the index of minima
// loop untill we find a price which is higher then buy price and its next is lower then current
while ((day < trade.length) && (trade[day] >= trade[day - 1])) {
day++;
}
// Store the index of maxima
e.sell = day - 1;
tradeDays.add(e);
}
if (tradeDays.isEmpty())
System.out.println("There is no day when buying the stock will make profit");
else
IntStream.range(0, tradeDays.size()).mapToObj(j -> "Buy on day: " + tradeDays.get(j).buy + " Sell on day : " + tradeDays.get(j).sell).forEach(System.out::println);
return;
}
}