aboutsummaryrefslogtreecommitdiff
path: root/other/best_buy_sell_stock.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/best_buy_sell_stock.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directoryHEADmaster
Diffstat (limited to 'other/best_buy_sell_stock.cpp')
-rw-r--r--other/best_buy_sell_stock.cpp31
1 files changed, 31 insertions, 0 deletions
diff --git a/other/best_buy_sell_stock.cpp b/other/best_buy_sell_stock.cpp
new file mode 100644
index 0000000..31b2a17
--- /dev/null
+++ b/other/best_buy_sell_stock.cpp
@@ -0,0 +1,31 @@
+// 121. Best Time to Buy and Sell Stock
+#include "leetcode.h"
+
+/*
+ * given an array 'prices' where 'prices[i]' is the price of a given stock on
+ * the ith day. maximise profit by choosing a single day to buy one stock and
+ * choosing a diff day in future to sell stock. return maximum profit achievable
+ * from transaction.
+ */
+
+class Solution {
+public:
+ int maxProfit(vector<int> &prices) {
+ int lsf = INT_MAX, op = 0, pist = 0;
+ for (int i = 0; i < prices.size(); i++) {
+ if (prices[i] < lsf)
+ lsf = prices[i];
+ pist = prices[i] - lsf;
+ if (op < pist)
+ op = pist;
+ }
+ return op;
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> p1 = {7, 1, 5, 3, 6, 4}, p2 = {7, 6, 4, 3, 1};
+ cout << obj.maxProfit(p1) << endl; // expect: 5
+ cout << obj.maxProfit(p2) << endl; // expect: 0
+}