Advertisement
gelita

max profit

Mar 9th, 2020
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.88 KB | None | 0 0
  1. /*Say you have an array for which the ith element is the price of a given stock on day i.
  2.  
  3. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
  4.  
  5. Note that you cannot sell a stock before you buy one.
  6.  
  7. Example 1:
  8.  
  9. Input: [7,1,5,3,6,4]
  10. Output: 5
  11. Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
  12.              Not 7-1 = 6, as selling price needs to be larger than buying price.
  13. Example 2:
  14.  
  15. Input: [7,6,4,3,1]
  16. Output: 0
  17. Explanation: In this case, no transaction is done, i.e. max profit = 0.
  18. */
  19. var maxProfit = function(prices) {
  20.     let result = 0;
  21.     let min = prices[0];
  22.     for(let i = 1; i < prices.length; i++) {
  23.         min = Math.min(prices[i], min);
  24.         result = Math.max(result, prices[i] - min);
  25.     }
  26.     return result;
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement