Monday, June 25, 2018

Best time to buy & sell stock

Problem statement: Say you have an array for which the i-th element is the price of a given stock on day i .

If you were only permitted to complete at most one transaction (i.e. buy one &  sell one share of the stock), design an algorithm to find the maximum profit.

Example:
Input:  [7, 3, 6, 7, 2, 8, 5, 6]
Output: 
max difference: 8-2 = 6
  1. public class BuySellStock
  2. {
  3.   public static void main(String[] args)
  4.   {
  5.     int p[] =  { 7, 3, 6, 7, 2, 8, 5, 6 };
  6.     System.out.println(maxProfit(p));
  7.   }
  8.   static int maxProfit(int[] prices)
  9.   {
  10.     int maxProfit = 0;
  11.     int minPrice = Integer.MAX_VALUE;
  12.     for (int i = 0; i < prices.length; i++)
  13.     {
  14.       minPrice = Math.min(minPrice, prices[i]);
  15.       maxProfit = Math.max(maxProfit, prices[i] - minPrice);
  16.     }
  17.     return maxProfit;
  18.   }
  19. }
Output: 6

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...