알고리즘/자료구조

[LeetCode] 122. Best Time to Buy and Sell Stock II - Java

2023. 8. 25. 00:04
목차
  1. 문제
  2. 내 풀이
 

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

 

문제

더보기

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 at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

 

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

 

Constraints:

  • 1 <= prices.length <= 3 * 104
  • 0 <= prices[i] <= 104

 

가격 배열 prices가 주어지며 여기서 prices[i]는 i일에 주어진 주식의 가격이다.

매일 주식을 구매 또는 판매할 수 있지만, 주식은 최대 1주만 보유할 수 있고, 구매한 당일에도 바로 판매할 수 있다.

얻을 수 있는 최대 profit을 반환하는 문제이다.

 


 

내 풀이

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;

        for(int i=1; i<prices.length; i++){
            if(prices[i] > prices[i-1]){
                profit += prices[i] - prices[i-1];
            }
        }

        return profit;
    }
}

121번 Best Time to Buy and Sell Stock 을 푼 뒤여서 그런지 빠르게 풀 수 있었다.

주식을 살 때 그 가격을 이익에서 차감하는 것이 아니기 때문에,

바로 이전의 가격과 비교해서 주식 가격이 내렸다면 바로 판매한다고 가정하고 차익을 이익에 더해주는 형태로 풀이했다.

 

 

  • 시간복잡도 : O(n)
  • 공간복잡도 : O(1)

 

최적의 코드로 잘 풀이한 것 같다.

 

 

저작자표시 (새창열림)

'알고리즘 > 자료구조' 카테고리의 다른 글

[LeetCode] 189. Rotate Array - Java  (0) 2023.08.25
[LeetCode] 55. Jump Game - Java  (0) 2023.08.25
[LeetCode] 121. Best Time to Buy and Sell Stock - Java  (0) 2023.08.24
[LeetCode] 169. Majority Element - Java  (0) 2023.08.24
[LeetCode] 80. Remove Duplicates from Sorted Array II - Java  (0) 2023.08.24
  1. 문제
  2. 내 풀이
'알고리즘/자료구조' 카테고리의 다른 글
  • [LeetCode] 189. Rotate Array - Java
  • [LeetCode] 55. Jump Game - Java
  • [LeetCode] 121. Best Time to Buy and Sell Stock - Java
  • [LeetCode] 169. Majority Element - Java
jny0
jny0
성장일기
jny0
J N Y 0
jny0
  • 분류 전체보기 (192)
    • 트러블슈팅 (6)
    • Java (22)
    • HTML, CSS , JavaScript (7)
    • MySQL, DBMS (9)
    • GIT (6)
    • 객체지향의 사실과 오해 (3)
    • 자바 ORM 표준 JPA 프로그래밍 (13)
    • 알고리즘 (114)
      • 자료구조 (59)
      • 수학 (11)
      • 정렬 (2)
      • 그리디 (3)
      • DP (4)
      • 그래프 (3)
      • 탐색 (9)
      • 재귀 (2)
      • 문자열 (9)
      • 기타 (12)
    • CS (10)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 글쓰기
  • 관리

공지사항

인기 글

태그

  • 알고리즘
  • 프로그래머스
  • Java
  • JS
  • 스택
  • codeup
  • 그리디
  • JPA
  • DP
  • MySQL
  • 누적합
  • BFS
  • git
  • 자료구조
  • 백준
  • db
  • 영상후기
  • 구현
  • method
  • 투포인터

최근 댓글

최근 글

hELLO · Designed By 정상우.
jny0
[LeetCode] 122. Best Time to Buy and Sell Stock II - Java
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.