Advertisement
1988coder

122. Best Time to Buy and Sell Stock II

Dec 29th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.51 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 totalProfit = 0;
  17.         for (int i = 1; i < prices.length; i++) {
  18.             if (prices[i - 1] < prices[i]) {
  19.                 totalProfit += prices[i] - prices[i - 1];
  20.             }
  21.         }
  22.  
  23.         return totalProfit;
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement