Find Buy/Sell Prices in Array of Stock Values to Maximize Profit

Problem: You have given a stock prices for next 10 days. Find out: max benefit in best time complexity in buy and sell 1 share ?
Condition: Share must be sold any day after buying date.

For ex:
Share price in thousands
5 1 4 6 7 8 4 3 7 9
Max benefit 9 – 1 = 8 thousand

Solution:

The max benefit is the case where you buy at the lowest price and sell at the highest, with the condition that the buy has to be before sell.

public static int getMaxBenefit(int []S) 
{
 int maxBenefit = 0;
 int minPrice = Integer.MAX_VALUE;
 for (int i = 0; i < S.length; i++) 
 {
 maxBenefit = Math.max(maxBenefit, S[i] - minPrice);
 minPrice = Math.min(S[i], minPrice);
 }

 return maxBenefit;
}

Time Complexity: O(N)

0 Thoughts on “Find Buy/Sell Prices in Array of Stock Values to Maximize Profit

  1. Gangadhar on March 27, 2015 at 5:03 pm said:

    Here is answer :

    public class Question1 {

    /*Problem: You have given a stock prices for next 10 days. Find out: max benefit in best time complexity in buy and sell 1 share ?
    Condition: Share must be sold any day after buying date.

    For ex:
    Share price in thousands
    5 1 4 6 7 8 4 3 7 9
    Max benefit 9 – 1 = 8 thousand*/

    public static void main(String[] args) {

    int[] shares = {5,3,4,25,9,7};

    int maxbenifit = 0;
    int minbuy=0;
    int maxSell=0;

    int buyPrice = 0;
    int sellPrice = 0;

    for(int i=0;i<shares.length;i++){

    buyPrice = shares[i];

    for (int j = i+1; j 0 && sellPrice – buyPrice > maxbenifit){
    maxbenifit = sellPrice – buyPrice;
    minbuy = buyPrice;
    maxSell = sellPrice;

    /*System.out.println( ” min minbuy :” + minbuy );
    System.out.println( ” max maxSell :” + maxSell );
    System.out.println( ” max benifit :” + maxbenifit );
    System.out.println( “————————-”);*/

    }

    }

    }

    System.out.println( ” min pirce :” + minbuy );
    System.out.println( ” max pirce :” + maxSell );

    }

    }

  2. Aditya Sharma on November 18, 2016 at 10:20 am said:

    int a[]={7,6,23,19,10,11,9,3,15};
    Arrays.sort(a);
    int i =a[a.length-1]-a[0];
    System.out.println(a[a.length-1]+” , “+a[0]+” and difference is “+i);

Leave a Reply to Gangadhar Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation