엔지니어 게시판
LeetCode 솔루션 분류

[Easy - wk5 - Q3] 121. Best Time to Buy and Sell Stock

컨텐츠 정보

본문

121. 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.

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.

 

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 <= 105
  • 0 <= prices[i] <= 104

관련자료

댓글 3

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = 10000;
        int maxProfit = 0;

        for(int i=0; i<prices.length; i++){
            if(prices[i] < minPrice){
                minPrice = prices[i];
            }else if(prices[i] - minPrice > maxProfit){
                maxProfit = prices[i] - minPrice;
            }
        }
        
        return maxProfit;
    }
}

yuun님의 댓글

  • 익명
  • 작성일
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        '''
        7 1 5 4 6 4
          b       
                  s
        
        '''
        buy = 0
        mx = 0
        for sell in range(1, len(prices)):
            profit = prices[sell] - prices[buy]
            if profit < 0:
                buy = sell
                
            mx = max(mx, profit)
        return mx

dawn27님의 댓글

  • 익명
  • 작성일
JS
Runtime: 85 ms, faster than 92.92% of JavaScript online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 51.5 MB, less than 80.44% of JavaScript online submissions for Best Time to Buy and Sell Stock.

var maxProfit = function(prices) {
    
  let buy = prices[0]; // 1
  let profit = 0;
  
  for (let i = 1; i < prices.length; i++) {
    if (buy > prices[i]) {
      buy = prices[i];
    } else {
      profit = Math.max(prices[i]-buy, profit);
    }
  }
  return profit;
};
전체 404 / 13 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 574 명
  • 오늘 방문자 7,840 명
  • 어제 방문자 6,975 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,537 명
알림 0