1 minute read

Problem

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 <= 10^5
  • 0 <= prices[i] <= 10^4

Solution

Logic

  1. 배열에서 한 요소를 참조하고 있을 때, 발생할 수 있는 가장 큰 Profit은 해당 요소 이전 요소 중 가장 작은 요소에서 해당 요소를 뺀 값이다.

  2. 1번에서 구한 Profit 중 최대 값을 기록하면서 배열을 끝까지 참조한다.

  3. 기록된(가장 큰) Profit을 반환한다.

    Code

    class Solution {
     public int maxProfit(int[] prices) {
         int min = prices[0];
         int profit = 0;
         for (int i = 1; i < prices.length; i++) { // n - 1번
             if (prices[i] < min) min = prices[i];
             if (profit < prices[i] - min) profit = prices[i] - min;
         } return profit;
     }
    }
    

    Time Complexity

    • 배열 prices의 길이를 n이라 할 때, 코드의 수행 시간을 좌우하는 것은 for반복문의 n - 1번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment