Advertisement
1988coder

121. Best Time to Buy and Sell Stock

Dec 29th, 2018
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. /**
  2.  * One Pass
  3.  *
  4.  * Time Complexity: O(N)
  5.  *
  6.  * Space Complexity: O(1)
  7.  *
  8.  * N = length of prices array.
  9.  */
  10. class Solution {
  11.     public int maxProfit(int[] prices) {
  12.         if (prices == null || prices.length <= 1) {
  13.             return 0;
  14.         }
  15.  
  16.         int minPrice = Integer.MAX_VALUE;
  17.         int maxProfit = 0;
  18.         for (int price : prices) {
  19.             minPrice = Math.min(minPrice, price);
  20.             maxProfit = Math.max(maxProfit, price - minPrice);
  21.         }
  22.  
  23.         return maxProfit;
  24.     }
  25. }
  26.  
  27. /**
  28.  * Kadane's Algorithm. This is algorithm can be used if difference array of
  29.  * prices is given.
  30.  *
  31.  * Time Complexity: O(N)
  32.  *
  33.  * Space Complexity: O(1)
  34.  *
  35.  * N = length of prices array.
  36.  */
  37. class Solution {
  38.     public int maxProfit(int[] prices) {
  39.         if (prices == null || prices.length <= 1) {
  40.             return 0;
  41.         }
  42.  
  43.         int maxHere = 0;
  44.         int maxSoFar = 0;
  45.         for (int i = 1; i < prices.length; i++) {
  46.             maxHere = Math.max(0, maxHere + prices[i] - prices[i - 1]);
  47.             maxSoFar = Math.max(maxSoFar, maxHere);
  48.         }
  49.  
  50.         return maxSoFar;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement