Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f335eb2

Browse files
committed
Add a question
1 parent 1885156 commit f335eb2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,3 +1194,56 @@ const uniqueInOrder = iterable => {
11941194
---
11951195

11961196
**[⬆ 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+
const maxProfit = 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+
const maxProfit = 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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /