Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions buy_and_sell_stock_2.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
49 changes: 49 additions & 0 deletions peeking_iterator.java
Original file line number Diff line number Diff line change
@@ -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<Integer> {
Iterator<Integer> iterator;
Integer nextVal;
boolean hasPeeked;

public PeekingIterator(Iterator<Integer> 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;
}
}