Tuesday, March 22, 2016

Find best profitable stock sale


Write an efficient function that takes stock Prices Yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 ABC stock yesterday.

The indices are the time in minutes past trade opening time, which was 9:30am local time.
The values are the price in dollars of ABC stock at that time.
So if the stock cost $100 at 10:30am, stockPricesYesterday[60] = 100.

Solution#1:
public class Solution {
    public static int getMaxProfit (int[] yesterdayPrices) {
        int[] bestDeal= new int[]{-1,-1};
        int bestDealPrice =0;
        for(int i =0; i++; i <= yesterdayPrices.length - 1)
        {
            for (int j= i+1; j++; j <= yesterdayPrices.length)
            {
                if(bestDealPrice < (a[i]-a[j]))
                {
                    bestDeal[0]=i;
                    bestDeal[1]=j;
                    bestDealPrice=(a[i]-a[j]);
                }
            }
        }
        return bestDealPrice;
    }
    public static void main(String[] args) {
        // run your function through some test cases here
        // remember: debugging is half the battle!
        int[] stockPricesYesterday = new int[]{12, 6, 8, 4, 11, 9};
        System.out.println(getMaxProfit(stockPricesYesterday));
    }
}

Solution#2:
    public static int getMaxProfit (int[] yesterdayPrices) {
    int minAvailablePrice = yesterdayPrices[0];
    int maximumProfit = yesterdayPrices[1] - yesterdayPrices[0];

    for (int i = 1; i < stockPricesYesterday.length; i++) {
        int currentPrice = yesterdayPrices[i];

        int potentialProfit = currentPrice - minPrice;

        maximumProfit = Math.max(maximumProfit, potentialProfit);
        minAvailablePrice = Math.min(minAvailablePrice, currentPrice);
    }

    return maximumProfit;
}

No comments:

Post a Comment