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
20 changes: 20 additions & 0 deletions BestTimeToBuySellStock.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int valley = INT_MAX;
int peak = INT_MIN;
int i=0;
int profit = 0;
]
while (i< prices.size()-1) {
while (i<prices.size()-1 && prices[i] >= prices[i+1])
i++;
valley = prices[i];
while (i<prices.size()-1 && prices[i] <= prices[i+1]) //
i++;
peak = prices[i];
profit += (peak-valley);
}
return profit;
}
};
54 changes: 54 additions & 0 deletions peekingIterator.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Below is the interface for Iterator, which is already defined for you.
* **DO NOT** modify the interface for Iterator.
*
* class Iterator {
* struct Data;
* Data* data;
* public:
* Iterator(const vector<int>& nums);
* Iterator(const Iterator& iter);
*
* // Returns the next element in the iteration.
* int next();
*
* // Returns true if the iteration has more elements.
* bool hasNext() const;
* };
*/

class PeekingIterator : public Iterator {
public:
int nextEle;
int nextVal;
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
nextEle = Iterator::hasNext();
if (nextEle) {
nextVal = Iterator::next();
}
}

// Returns the next element in the iteration without advancing the iterator.
int peek() {
return nextVal;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
int oldVal = nextVal;

nextEle = Iterator::hasNext();
if (nextEle) {
nextVal = Iterator::next();
}
return oldVal;
}

bool hasNext() const {
return nextEle;
}
};