반응형
    
    
    
  
													Recent Posts
													
											
												
												
													
														Notice
														
												
											
												
												
													Recent Comments
													
											
												
												
													Link
													
											250x250
    
    
  | 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 
| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
| 19 | 20 | 21 | 22 | 23 | 24 | 25 | 
| 26 | 27 | 28 | 29 | 30 | 31 | 
													Tags
													
											
												
												- 리트코드
- leetcode
- DP
- 깊이우선탐색
- Java
- Algorithm
- dfs
- greedy
- 부분배열
- two pointers
- 재귀함수
- coding
- priority queue
- 알고리즘
- hashset
- PCCP
- Array
- string
- HashMap
- 우선순위 큐
- ArrayList
- programmers
- binary tree
- recursion
- 브루트포스
													Archives
													
											
												
												- Today
- Total
지식창고
[Java] LeetCode 121. Best Time to Buy and Sell Stock 본문
728x90
    
    
  반응형
    
    
    
  [Java] LeetCode 121. Best Time to Buy and Sell Stock
문 제 :
날에 따른 주식의 가격을 나타내는 일 차원 정수 배열 prices[] 가 주어진다.
주식을 한 개 사서 판다고 가정했을 때, 가장 최대의 이익을 얻을 수 있을 때, 그 이익은 얼마인가?
Constraint
{ 1 <= prices.length <= 10^5 }
{ 0 <= prices[i] <= 10^4 }
Example )
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.
//////////////////////////////////////////////////////////
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: 
In this case, no transactions are done and the max profit = 0.
접   근 : 
최소의 가격으로 사서 최대의 가격에 판다.
해 결 :
prices배열을 돌면서 가장 싼 주식을 최신화 해준다.
가장 싼 주식을 현재가에 팔았을 때의 이익을 최대이익과 비교해 최신화 해준다.
결 과 :
class Solution {
    public int maxProfit(int[] prices) {
        int profit=0;
        int buyStock = Integer.MAX_VALUE;
        for(int i=0; i<prices.length; i++){
            buyStock = Math.min(buyStock, prices[i]);
            profit = Math.max(profit, prices[i] - buyStock);
        }
        return profit;
    }
}728x90
    
    
  반응형
    
    
    
  'Algorithm > Leetcode' 카테고리의 다른 글
| [Java] LeetCode 2444. Count Subarrays With Fixed Bounds (0) | 2023.03.04 | 
|---|---|
| [Java] LeetCode 443. String Compression (1) | 2023.03.02 | 
| [Java] LeetCode 1011. Capacity To Ship Packages Within D Days (0) | 2023.02.22 | 
| [Java] LeetCode 122. Best Time to Buy and Sell Stock II (0) | 2023.02.21 | 
| [Java] LeetCode 540. Single Element in a Sorted Array (2) | 2023.02.21 | 
			  Comments