Skip to content

Commit

Permalink
add a new simpler solution
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Feb 2, 2019
1 parent 7249bc3 commit 4d762f4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@

class Solution {
public:
//
int maxProfit(vector<int>& prices) {
return maxProfit02(prices);
return maxProfit01(prices);
}
// Solution 1
// find all of ranges: which start a valley with the nearest peak after
// add their delta together
//
int maxProfit(vector<int> &prices) {
int maxProfit01(vector<int> &prices) {

int max = 0;
int low = -1;
Expand All @@ -43,4 +47,14 @@ class Solution {

return max;
}

// Solution 2
// if we find we can earn money, we just sell
int maxProfit02(vector<int>& prices) {
int profit = 0 ;
for(int i=1; i< prices.size(); i++) {
profit += max(0, prices[i] - prices[i-1]);
}
return profit;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,19 @@ class Solution {

}
};


class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy = INT_MAX;
int profit = 0;
for (auto p : prices) {
// Keep tracking the previous lowest price
buy = min (buy, p);
// Keep tacking the current max profit
profit = max(profit, p - buy);
}
return profit;
}
};

0 comments on commit 4d762f4

Please sign in to comment.