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

2023. 8. 25. 03:19·알고리즘/leet code
 

Best Time to Buy and Sell Stock II - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock II - You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold

leetcode.com

문제 설명

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

문제 해결

  • 배열의 연속된 요소 2개를 비교하여 양수일 때(그래프가 증가하는 경우)의 값들을 모두 합산하여 반환한다.
  • 그래프를 그려보면 감소하는 것은 무시하고 증가하는 부분만을 합산하였을 때 가장 높은 이익의 합을 반환하는 것을 알 수 있다.

시간 복잡도

  • O(N-1)

풀이 코드

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

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

결과

시간 메모리
1 ms 44.3 MB

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

[알고리즘] LeetCode - Valid Palindrome  (0) 2023.08.28
[알고리즘] LeetCode - Jump Game  (0) 2023.08.25
[알고리즘] LeetCode - Best Time to Buy and Sell Stock  (0) 2023.08.25
[알고리즘] LeetCode - Rotate Array  (0) 2023.08.25
[알고리즘] LeetCode - Majority Element  (0) 2023.08.24
'알고리즘/leet code' 카테고리의 다른 글
  • [알고리즘] LeetCode - Valid Palindrome
  • [알고리즘] LeetCode - Jump Game
  • [알고리즘] LeetCode - Best Time to Buy and Sell Stock
  • [알고리즘] LeetCode - Rotate Array
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)
  • 태그

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

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

티스토리툴바