diff --git a/buy_and_sell_stock_2.java b/buy_and_sell_stock_2.java new file mode 100644 index 0000000..b29cff2 --- /dev/null +++ b/buy_and_sell_stock_2.java @@ -0,0 +1,26 @@ +// Time Complexity : O(n) because we traverse the array once +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach in three sentences only +// We greedily capture every increasing price difference as profit. +// Any continuous upward trend can be split into multiple buy-sell transactions without changing the total profit. +// Adding all positive differences gives the maximum possible profit. + +class Solution { + public int maxProfit(int[] prices) { + int profit = 0; + + for(int i = 1; i < prices.length; i++) { + + // take profit from every upward move + if(prices[i] > prices[i - 1]) { + profit += prices[i] - prices[i - 1]; + } + } + + return profit; + } +} \ No newline at end of file diff --git a/peeking_iterator.java b/peeking_iterator.java new file mode 100644 index 0000000..375f183 --- /dev/null +++ b/peeking_iterator.java @@ -0,0 +1,49 @@ +// Time Complexity : O(1) for peek(), next(), and hasNext() +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach in three sentences only +// We store the next element in advance so peek() can return it without moving the iterator. +// next() returns the stored value and immediately fetches the following element. +// hasNext() simply checks whether a prefetched value is available. + +class PeekingIterator implements Iterator { + Iterator iterator; + Integer nextVal; + boolean hasPeeked; + + public PeekingIterator(Iterator iterator) { + this.iterator = iterator; + advance(); + } + + // prefetch next element + private void advance() { + if(iterator.hasNext()) { + nextVal = iterator.next(); + hasPeeked = true; + } else { + nextVal = null; + hasPeeked = false; + } + } + + // return next element without advancing + public Integer peek() { + return nextVal; + } + + @Override + public Integer next() { + int ans = nextVal; + advance(); + return ans; + } + + @Override + public boolean hasNext() { + return hasPeeked; + } +} \ No newline at end of file