알고리즘/문제

[LeetCode] - E - Best Time to Buy and Sell Stock

Casteira 2023. 8. 25. 02:31

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? 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 choosin

leetcode.com

 

📌 - 의사 코드

  1. result =0, max, min을 배열의 첫번째 값으로 초기화
  2. for문으로 1번째 부터 비교를 하면서 해당 하는 값이 min보다 작다면 max와 min을 prices[i]로 업데이트
  3. prices[i]가 max보다 클 경우 max를 업데이트
  4. result 값과 max - min을 비교하면서 큰 값을 result로 변경

 

 

🔥 - Java 코드

 

class Solution {
    public int maxProfit(int[] prices) {
        int result =0;
        int max = prices[0], min = prices[0];
        for(int i=1;i<prices.length;i++){
            if(prices[i] < min){
                max = prices[i];
                min = prices[i];
            }

            if(prices[i] > max){
                max = prices[i];
            }

            result = Math.max(result, max-min);
        }

        return result;

    }
}