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
15 changes: 15 additions & 0 deletions best-time-to-buy-and-sell-stock-ii.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(1)
// Explanation: I am solving the problem by adding all positive price differences between consecutive days. If the price on the next day is higher than the current day, I add the difference to the total profit because it represents a valid buy and sell opportunity. This approach works because multiple small profitable transactions are equivalent to one larger transaction in terms of total profit.

class Solution {
public int maxProfit(int[] prices) {
int profit =0;
for(int i=0; i<prices.length-1; i++) {
if(prices[i]<prices[i+1]) {
profit = profit + prices[i+1] - prices[i];
}
}
return profit;
}
}
50 changes: 50 additions & 0 deletions peeking-iterator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// TimeComplexity : O(1)
// SpaceComplexity : O(1)
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator implements Iterator<Integer> {
private Integer nextEl;
private Iterator<Integer> iter;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iter = iterator;
if (iterator.hasNext()) {
this.nextEl = iterator.next();
}
}

// Returns the next element in the iteration without advancing the iterator.
// TimeComplexity: O(1)
// SpcaeComplexity: O(1)
public Integer peek() {
return this.nextEl;

}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
// TimeComplexity: O(1)
// SpcaeComplexity: O(1)
@Override
public Integer next() {

Integer result = nextEl;

if (iter.hasNext()) {
nextEl = iter.next();
} else {
nextEl = null;
}

return result;
}

@Override
// TimeComplexity: O(1)
// SpcaeComplexity: O(1)
public boolean hasNext() {
return (this.nextEl!=null);

}
}