We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static long stockmax(List<Integer> prices) {
// Write your code here
// Find the max val of the list and find the index. If the index of max val is 0 then no profit can be made and return 0.
// else profit can be made. Sell the stock at the max index.
// Corner case, need to check the max index for the remaining sub-list after max index to verify the another opportunity.
long profit = 0L;
int maxIndex = prices.indexOf(Collections.max(prices));
if(maxIndex == prices.size()-1){
return getProfitFromSubList(prices);
}
else{
List<Integer> subList1 = prices.subList(0,maxIndex+1);
List<Integer> subList2 = prices.subList(maxIndex+1, prices.size());
profit = getProfitFromSubList(subList1);
profit += stockmax(subList2);
}
return profit;
}//method
public static long getProfitFromSubList(List<Integer> subList){
long costPrice = 0L;
int cnt = 0;
for(int i =0; i < subList.size()-1; i++){
costPrice += subList.get(i);
cnt++;
}
long sellPrice = subList.get(subList.size()-1) * cnt;
return sellPrice-costPrice;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Stock Maximize
You are viewing a single comment's thread. Return to all comments →
Java 8 solution using Recurssive method calls: