diff --git a/problem1.java b/problem1.java new file mode 100644 index 0000000..331ec7c --- /dev/null +++ b/problem1.java @@ -0,0 +1,19 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Approach : Best time to sell stock and buy, maximum profit can be achived when we buy and sell the stock at each positive slope. Hence, +// we maintain profit and add to it whenever we come across a positive slope, which means buy and sell a stock whenever first profit comes. + + +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int profit = 0; + for(int i = 0; i < n - 1; i++){ + if(prices[i+1] > prices[i]){ //check if next value is greater than current + profit += prices[i+1] - prices[i]; //sell and add to profit + } + } + return profit; + } +} \ No newline at end of file diff --git a/problem2.java b/problem2.java new file mode 100644 index 0000000..8feebc0 --- /dev/null +++ b/problem2.java @@ -0,0 +1,48 @@ +// Time Complexity : O(1) for peek(), next() and hasNext() +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Approach : Peeking iterator:The idea is to stay one step ahead as we cannot comeback when next() is performed on an iterartor. +// So during intialization itself, we perform next and store the first element in bufferedVal. If peek() is called, +// we return that value in bufferedValue. If next is called, we need to return the current bufferedVal and also move to the next pointer +// and store that value. hasNext() will return true if we have a value in bufferdValue. + + +class PeekingIterator implements Iterator { + Iterator it; + int bufferedVal; //to store the value in advance + public PeekingIterator(Iterator iterator) { + // initialize any member here. + this.it = iterator; + if(it != null && it.hasNext()){ //store the next value at intialization + bufferedVal = it.next(); + }else{ + bufferedVal = 0; + } + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + if(bufferedVal > 0){ //if present, return + return bufferedVal; + } + return -1; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + int temp = bufferedVal; //store in temp + if(it.hasNext()){ + bufferedVal = it.next(); //advance and store the next + }else{ + bufferedVal = 0; + } + return temp; //return temp + } + + @Override + public boolean hasNext() { + return bufferedVal > 0; + } +} \ No newline at end of file