You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
**[⬆ Back to Top](#javascript-coding-challenges-for-beginners)**
1197
+
1198
+
## 38. Best Time to Buy and Sell Stock
1199
+
1200
+
You are given an array `prices` where `prices[i]` is the price of a given stock on the `i`th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return `0`.
1201
+
1202
+
Example 1:
1203
+
1204
+
```
1205
+
Input: prices = [7,1,5,3,6,4]
1206
+
Output: 5
1207
+
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
1208
+
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
1209
+
```
1210
+
1211
+
Example 2:
1212
+
1213
+
```
1214
+
Input: prices = [7,6,4,3,1]
1215
+
Output: 0
1216
+
Explanation: In this case, no transactions are done and the max profit = 0.
1217
+
```
1218
+
1219
+
```js
1220
+
constmaxProfit=prices=> {
1221
+
// Your solution
1222
+
};
1223
+
1224
+
console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 5
1225
+
console.log(maxProfit([7, 6, 4, 3, 1])); // 0
1226
+
```
1227
+
1228
+
<details><summary>Solution</summary>
1229
+
1230
+
```js
1231
+
constmaxProfit=prices=> {
1232
+
let min =Number.MAX_SAFE_INTEGER;
1233
+
let profit =0;
1234
+
1235
+
for (let i =0; i <prices.length; i++) {
1236
+
min =Math.min(prices[i], min);
1237
+
if (prices[i] - min > profit) {
1238
+
profit = prices[i] - min;
1239
+
}
1240
+
}
1241
+
return profit;
1242
+
};
1243
+
```
1244
+
1245
+
</details>
1246
+
1247
+
---
1248
+
1249
+
**[⬆ Back to Top](#javascript-coding-challenges-for-beginners)**
0 commit comments