diff --git a/121/1.cpp b/121/1.cpp new file mode 100644 index 0000000..05d1a7f --- /dev/null +++ b/121/1.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxProfit(vector& prices) { + vector minPricesFromStart; + vector maxPricesFromEnd; + + int minPrice = INT_MAX; + for(int i = 0; i < prices.size(); i++){ + minPrice = min(minPrice, prices[i]); + minPricesFromStart.push_back(minPrice); + } + int maxPrice = -1; + for(int i = prices.size()-1; i >= 0; i--){ + maxPrice = max(maxPrice, prices[i]); + maxPricesFromEnd.push_back(maxPrice); + } + reverse(maxPricesFromEnd.begin(), maxPricesFromEnd.end()); + + int maxProfit = 0; + for(int i = 0; i < prices.size(); i++){ + int currentProfit = maxPricesFromEnd[i] - minPricesFromStart[i]; + maxProfit = max(maxProfit, currentProfit); + } + return maxProfit; + } +}; diff --git a/121/2.cpp b/121/2.cpp new file mode 100644 index 0000000..79b34ef --- /dev/null +++ b/121/2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int maxPrice = 0; + int minPrice = INT_MAX; + int maxProfit = 0; + for (int i = 0; i < prices.size(); i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; + } else { + maxPrice = prices[i]; + int currentProfit = maxPrice - minPrice; + maxProfit = max(maxProfit, currentProfit); + } + } + return maxProfit; + } +}; diff --git a/121/3.cpp b/121/3.cpp new file mode 100644 index 0000000..e2e117e --- /dev/null +++ b/121/3.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxProfit(vector& prices) { + int minPrice = INT_MAX; + int maxProfit = 0; + for(int i = 0; i < prices.size(); i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; + } else { + maxProfit = max(maxProfit, prices[i] - minPrice); + } + } + + return maxProfit; + } +}; diff --git a/121/4.cpp b/121/4.cpp new file mode 100644 index 0000000..885bf82 --- /dev/null +++ b/121/4.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxProfit(vector& prices) { + if(prices.empty())abort(); + + int minPrice = prices[0]; + int currentProfit = 0; + for(int price: prices) { + if (price < minPrice) { + minPrice = price; + } else { + currentProfit = max(currentProfit, price - minPrice); + } + } + + return currentProfit; + } +};