From 3a02f8d38bd9daeabaadbd44c4f4ef5f754fe2f2 Mon Sep 17 00:00:00 2001 From: PrasiddhShah Date: Tue, 9 Dec 2025 13:18:46 -0800 Subject: [PATCH] Cometitive-coding-10-complete --- problem1.java | 22 ++++++++++++++++++++++ problem2.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 problem1.java create mode 100644 problem2.java diff --git a/problem1.java b/problem1.java new file mode 100644 index 0000000..3024c67 --- /dev/null +++ b/problem1.java @@ -0,0 +1,22 @@ +// Time Complexity :O(n) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this :no + +/* +Approach +idea here is to buy only if the next day the price goes up +single pass as we are only deal this the next ele to i +*/ + +class Solution { + public int maxProfit(int[] prices) { + int total = 0; + for (int i = 0; i < prices.length - 1; i++) { + if (prices[i] < prices[i + 1]) { + total += prices[i + 1] - prices[i]; + } + } + return total; + } +} \ No newline at end of file diff --git a/problem2.java b/problem2.java new file mode 100644 index 0000000..d0ca7b3 --- /dev/null +++ b/problem2.java @@ -0,0 +1,51 @@ +// Time Complexity :O(1) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this :no + +/* +Approach +we are using a native iterator to implement this iterator, +you native iterator is alway one ele ahead of the peeking iterator + +when the peeking iterator is initialised we store the first ele + +if peek it called we just return the value of the stored ele + +if next is called, as we alreay have the next value stored in ele we return that value but +before we return we check if there is a next ele if yes we save that + +if hasnext it checks if nextEl is null or not, and returns accordingly +*/ + +class PeekingIterator implements Iterator { + Iterator iter; + Integer nextEl; + + public PeekingIterator(Iterator iterator) { + this.iter = iterator; + this.nextEl = iter.next(); + } + + public Integer peek() { + return nextEl; + } + + @Override + public Integer next() { + Integer temp = nextEl; + nextEl = null; + if (iter.hasNext()) { + nextEl = iter.next(); + } + return temp; + } + + @Override + public boolean hasNext() { + if (nextEl != null) { + return true; + } + return false; + } +} \ No newline at end of file