# Leetcode - Best Time to Buy and Sell Stock

·2022년 2월 1일
0

목록 보기
16/19

## Problem

Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.

prices라는 배열이 주어지고 prices[i]ith 날의 주가 일때

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.

이 거래에서 얻을 수 있는 최대 이익을 구하시오. 만약 이익이 없다면 0을 반환한다

#### Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

#### Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

#### Constraints:

• 1 <= prices.length <= 10⁵
• 0 <= prices[i] <= 10⁴

## Solution

#### JavaScript

/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let left = 0
let profit = 0

for(let right = 0; right < prices.length; right++) {
if(prices[left] > prices[right]) left = right

profit = Math.max(profit, prices[right] - prices[left])
}

return profit
};

Feedback은 언제나 환영입니다🤗

You only get one life. It's actually your duty to live it as fully as possible.