• Source
    1. import java.util.*;
    2.  
    3. /*
    4.  * Best days to buy and sell stock, if array of stock prices given
    5.  *
    6.  *Q: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to
    7.  * buy one share of the stock and sell one share of the stock, design an algorithm to find the best times to buy and sell
    8.  *
    9.  * Algorithm: Go through the array in order, keeping track of the lowest stock price and the best deal you've seen so far.
    10.  * Whenever the current stock price minus the current lowest stock price is better than the current best deal,
    11.  * update the best deal to this new value.
    12.  *
    13.  */
    14. class Ideone{
    15.  
    16. public static void main(String[] args){
    17. int[] a = { 5, 3, 8, 12, 6, 7, 9, 3, 21, 6 };
    18.  
    19. int bestBuy = a[0];
    20. int bestSell = a[0];
    21.  
    22. int tempBuy = a[0];
    23. int tempSell = a[0];
    24.  
    25. //Traverse across array and look for an element which will give max profit.
    26. for(int i=1; i<a.length; i++){
    27. if(a[i]> tempSell){ //If you find element value is more than tempSell, there is possibility to sell
    28. tempSell = a[i];
    29. if(tempSell-tempBuy > bestSell-bestBuy){
    30. bestBuy = tempBuy;
    31. bestSell = tempSell;
    32. }
    33. }else if(a[i]<tempBuy){
    34. tempBuy = a[i];
    35. }
    36. }
    37. System.out.println("Best day to buy => "+ bestBuy + " best time to sell =>"+ bestSell);
    38. }
    39. }
    40.