우규이인우윤
Eager To Learn 🌌
우규이인우윤
전체 방문자
오늘
어제

블로그 메뉴

  • 🏡 홈
  • 🚀 깃허브
  • ⛅ 태그 클라우드
  • 분류 전체보기 (217)
    • 👨🏻‍💻 PS (170)
      • JAVA (82)
      • MYSQL (1)
      • Docker (2)
      • PYTHON (24)
      • LeetCode 150 (39)
      • Algorithm 기법 (1)
      • 바킹독 (21)
    • 블로그 이사 (0)
    • Error (1)
    • CS (15)
      • DataBase (2)
      • OS (7)
      • Network (1)
      • Spring (1)
      • 자료구조 (3)
      • Java (1)
    • Learned (7)
      • Spring (7)
    • 개발서적 (15)
      • 가상 면접 사례로 배우는 대규모 시스템 설계 기초 (1)
      • 오브젝트 - 조영호 (7)
      • 친절한 SQL 튜닝 (7)
    • 회고 (2)
hELLO · Designed By 정상우.
우규이인우윤

Eager To Learn 🌌

👨🏻‍💻 PS/PYTHON

[파이썬 PYTHON · 자바 JAVA] LeetCode【Best Time to Buy and Sell Stock】

2023. 3. 10. 18:42

 

 

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


파이썬 코드

class Solution(object):
    def maxProfit(self, prices):
        buy = prices[0]
        ans = 0
        for price in prices:
            if price>buy:
                ans = max(ans,price-buy)
            else:
                buy = price
        return ans

자바코드

import java.util.*;
class Solution {
    public int maxProfit(int[] prices) {
        int buy = prices[0];
        int ans = 0;
        for(int i=1;i<prices.length;i++){
            if(prices[i]<buy){
                buy = prices[i];
            }else{
                ans = Math.max(ans,prices[i]-buy);
            }
        }

        return ans;
    }
}

 

buy는 사는 가격이다.

 

가격이 낮아지는 경우에는 buy를 갱신하고

 

가격이 높아지면 max()로 이익을 계속 업데이트해준다.

 

[7,1,5,3,6,4]

위 예제로 원리를 살펴보면

 

1. buy = 7 / prices[0] = 7 이므로 buy를 7로 업데이트한다.

 

ans = 0

 

2. buy = 7 / prices[1] = 1 이므로 가격이 낮아지면 이익이 어차피 존재하지 않으므로 buy를 1로 업데이트한다.

 

ans = 0

 

3. buy = 1 / prices[2] = 5 이므로 차익을 기록해둔다.

 

ans = 4

 

4. buy = 1 / prices[3] = 3 이므로 차익이 2지만, 기록해둔 4보다 작으므로 기록하지 않는다.

 

ans = 4

 

5. buy = 1 / prices[4] = 6 이므로 차익이 5이고 기존 4보다 크므로 업데이트한다.

 

ans = 5

 

6. buy = 1 /prices[5] = 4 이므로 차익이 3이고 기존 5보다 작으므로 업데이트 하지 않는다.

 

결과적으로 답은 5가 나온다.

 

 

    '👨🏻‍💻 PS/PYTHON' 카테고리의 다른 글
    • [파이썬 PYTHON · 자바 JAVA] LeetCode【Product of Array Except Self】
    • [파이썬 PYTHON · 자바 JAVA] LeetCode【Contains Duplicate】
    • [파이썬 PYTHON · 자바 JAVA] LeetCode【Two sum】
    • [파이썬 PYTHON] 백준 2146번 【다리 만들기】
    우규이인우윤
    우규이인우윤
    개발자 꿈나무

    티스토리툴바