Advertisement
gelita

Leetcode 121 Java Best time to buy and sell stock

Jan 2nd, 2020
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.67 KB | None | 0 0
  1. /***
  2. *Say you have an array for which the ith element is the price of a given stock on day i.
  3. *Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of *the stock multiple times).
  4. *Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
  5. ***/
  6.  
  7. class Solution {
  8.     public int maxProfit(int[] prices) {
  9.     if(prices.length == 0){
  10.         return 0;
  11.     }
  12.     int maxProfit = 0;
  13.     int min = prices[0];
  14.     for(int i = 1; i < prices.length; i++) {
  15.         min = Math.min(prices[i], min);
  16.         maxProfit = Math.max(maxProfit, prices[i] - min);
  17.     }
  18.     return maxProfit;
  19.   }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement