Leetcode - 121. Best Time to Buy and Sell Stock
Coding Test

Leetcode - 121. Best Time to Buy and Sell Stock

일시불

문제

Loading...
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

정답

파이썬

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        left = 0
        right = 1
        profit = 0
        
        while right < len(prices):
            if prices[right] - prices[left] > 0:
                profit = max(profit, prices[right]-prices[left])
            else:
                left = right
                
            right += 1
            
        return profit

러스트

use std::cmp::max;

impl Solution {
    pub fn max_profit(prices: Vec<i32>) -> i32 {
        let mut left = 0;
        let mut profit = 0;

        for right in 1..prices.len() {
            if prices[right] - prices[left] > 0 {
                profit = max(profit, prices[right] - prices[left]);
            } else {
                left = right;
            }
        }

        profit
    }
}