[알고리즘] LeetCode - Best Time to Buy and Sell Stock

2023. 8. 25. 02:06·알고리즘/leet code
 

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

문제 설명

  • 해당 날짜의 특정 주식 가격을 나타내는 정수형 배열 prices가 주어진다.
  • 특정 날짜에 주식을 매수하고 특정 날짜에 주식을 매도했을 때 낼 수 있는 가장 높은 이익을 반환해야 한다.

문제 해결

  • 반복문을 돌면서 정수형 변수 min값을 최솟값으로 갱신해준다.
  • 반복문을 돌면서 (현재 자리의 수 - min) 값을 answer에 최댓값으로 갱신해준다.

시간 복잡도

  • O(N)

풀이 코드

class Solution {
    public int maxProfit(int[] prices) {
        int N = prices.length;
        int answer = 0;
        int min = 10000;

        for (int i = 0; i < N; i++) {
            int sub = prices[i] - min;
            answer = Math.max(answer, sub);
            min = Math.min(min, prices[i]);
        }
        return answer;
    }
}

결과

시간 메모리
1 ms 61.4 MB

'알고리즘 > leet code' 카테고리의 다른 글

[알고리즘] LeetCode - Jump Game  (0) 2023.08.25
[알고리즘] LeetCode - Best Time to Buy and Sell Stock II  (0) 2023.08.25
[알고리즘] LeetCode - Rotate Array  (0) 2023.08.25
[알고리즘] LeetCode - Majority Element  (0) 2023.08.24
[알고리즘] LeetCode - Remove Duplicates from Sorted Array II  (0) 2023.08.24
'알고리즘/leet code' 카테고리의 다른 글
  • [알고리즘] LeetCode - Jump Game
  • [알고리즘] LeetCode - Best Time to Buy and Sell Stock II
  • [알고리즘] LeetCode - Rotate Array
  • [알고리즘] LeetCode - Majority Element
tableMinPark
tableMinPark
Backend Engineer
  • tableMinPark
    Sangmin's Tech Blog
    tableMinPark
  • 전체
    오늘
    어제
  • 블로그 메뉴

    • tech study blog
    • my github
    • monglife github
    • 분류 전체보기 (48)
      • 개발 (7)
        • java (0)
        • kotlin (0)
        • spring boot (0)
        • android (0)
        • junit5 (5)
        • architecture (2)
      • 데브옵스 (3)
        • docker (3)
        • github action (0)
        • grafana (0)
        • prometheus (0)
        • elk (0)
      • 알고리즘 (35)
        • baek joon (0)
        • programmers (4)
        • leet code (29)
      • 일상 (3)
        • Wear OS 앱 개발기 (2)
        • 회고 (1)
  • 태그

    monglife
    Android
    jetpack-compose
    20.04
    docker network
    Thread
    MSA
    mongs
    docker-compose
    Kotlin
    docker compose
    ubuntu
    volume
    Container
    java
    레이어드 아키텍처
    bind mount
    Galaxy watch
    MVVM
    docker
    apple watch
    micro service
    wear os
    synchronized
    layered architecture
  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
tableMinPark
[알고리즘] LeetCode - Best Time to Buy and Sell Stock
상단으로

티스토리툴바