From c438ab76dfc6532abff937f827fe2cbbd941e309 Mon Sep 17 00:00:00 2001 From: subbu4061 Date: Mon, 2 Mar 2026 14:27:38 -0800 Subject: [PATCH] Adding all the solutions --- best-time-to-buy-and-sell-stock-ii.java | 15 ++++++++ peeking-iterator.java | 50 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock-ii.java create mode 100644 peeking-iterator.java diff --git a/best-time-to-buy-and-sell-stock-ii.java b/best-time-to-buy-and-sell-stock-ii.java new file mode 100644 index 0000000..40f4596 --- /dev/null +++ b/best-time-to-buy-and-sell-stock-ii.java @@ -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 { + private Integer nextEl; + private Iterator iter; + public PeekingIterator(Iterator 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); + + } +} \ No newline at end of file