Wednesday 17 August 2016


/* 
 * Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like
 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in
  multiple transactions at the same time (ie, you must sell the stock before you buy again).
 *  */
public class BuySellStock {
    private static boolean typeOfAction;
    private int profit;
    public int maxProfit(int[] prices) {
        if(prices.length==1){
            return 0;
        }
        for (int i = 0; i < prices.length; i++) {
            if(i==0){//first type of action handle
                if(prices[i]<prices[i+1]){
                    typeOfAction = true;
                }
            }
            if(i==prices.length-1){
                if(!typeOfAction){//last element handle - only sell
                    sell(prices[i]);
                }
            }else{
                if(typeOfAction){//buy
                    if(prices[i+1] > prices[i]){
                        buy(prices[i]);
                    }
                }else{//sell
                    if(prices[i+1] < prices[i]){
                        sell(prices[i]);
                    }
                }
            }
        }
       
       
        return profit;
       
    }
   
    private void buy(int amt){
        profit = profit - amt;
        typeOfAction = false;
    }
   
    private void sell(int amt){
        profit = profit + amt;
        typeOfAction = true;
    }
    public static void main(String[] args) {
        int[] array ={8,5,3,7,4,9,11};
        BuySellStock s = new BuySellStock();
        ;
        System.out.println(s.maxProfit(array));
       
       
    }
}