가장 쌀 때 사서 비싸게 파는 경우를 찾는 문제이므로, 파는 것을 기준으로 순회 하였으면,
값을 체크해서 가장 낮은 금액일 경우 해당 금액을 사는 날로 변경하였다.

시간의 개념이 들어가므로 파는 날짜보다 사는 날짜가 이전에 있어야 하기 때문에 무작정 최소 값을 사는 기준으로 하는 것이 아니라 파는 날짜를 순회해서 기준이 되는 날짜를 찾았다.

public class Solution {  
    public int maxProfit(int[] prices) {  
        int maxProfit = 0;  
        int minPrice = prices[0];  
        int buy = 0;  
  
        // 매일 파는 값을 체크, 사는 지점은 값(minPrice)이 가장 낮은 지점일 때  
        for(int sell = 1; sell < prices.length; sell++){  
            int buyPrice = prices[buy];  
            int sellPrice = prices[sell];  
            int curProfit = sellPrice - buyPrice;  
  
            // 최저가일 경우 구매점으로 변경  
            if(sellPrice < minPrice){  
                buy = sell;  
                minPrice = sellPrice;  
                continue;  
            }  
  
            maxProfit = Math.max(curProfit, maxProfit);  
        }  
  
        return maxProfit;  
    }  
}

'Algolithm-Leetcode > Sliding Window' 카테고리의 다른 글

Sliding Window Maximum  (0) 2026.08.25
Longest Repeating Character Replacement  (0) 2026.08.21
Minimum Window Substring  (0) 2026.08.15
Longest Substring Without Repeating Characters  (0) 2026.08.09

https://leetcode.com/problems/two-sum/description/

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not

leetcode.com

 

 

두 값의 합이 Target과 일치하는 인덱스를 배열로 반환하는 문제이다.
알고리즘이 필요하기보다. 배열을 다룰 수 있는 지에 가까운 문제였다.

class Solution {
public int[] twoSum(int[] nums, int target){  
    for(int i = 0; i < nums.length; i++){  
        for(int j = i + 1; j < nums.length; j++){  
            if(nums[i] + nums[j] == target){  
                return new int[]{i, j};  
            }  
        }  
    }  
	return null;  
}

 

 

문제에서 반드시 하나의 답이 존재한다고 조건을 주어서 순회가 끝난 경우 null 로 처리하였다.
Exception으로 처리하려 하였으나 리트코드에서는 문제에서 별도의 익셉션 처리를 할 수 없는 듯 하였다. throws Exception 메세지를 추가하자 아래와 같은 오류가 발생하였다.

Line 7: error: unreported exception Exception; must be caught or declared to be thrown [in __Driver__.java] int[] ret = new Solution().twoSum(param_1, param_2); ^

 

로드맵의 첫 문제라서 그런지 굉장히 쉬웠다.

'Algolithm-Leetcode > Arrays & Hashing' 카테고리의 다른 글

Top K Frequent Elements  (0) 2026.08.23
Group Anagrams  (0) 2026.08.20
Contains Duplicate  (0) 2026.08.14
Valid Anagram  (0) 2026.08.07

+ Recent posts