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
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
- public class BuySellStock
- {
- public static void main(String[] args)
- {
- int p[] = { 7, 3, 6, 7, 2, 8, 5, 6 };
- System.out.println(maxProfit(p));
- }
- static int maxProfit(int[] prices)
- {
- int maxProfit = 0;
- int minPrice = Integer.MAX_VALUE;
- for (int i = 0; i < prices.length; i++)
- {
- minPrice = Math.min(minPrice, prices[i]);
- maxProfit = Math.max(maxProfit, prices[i] - minPrice);
- }
- return maxProfit;
- }
- }
Output: 6
No comments:
Post a Comment