Array
-
[array] best time to buy and sell stock 2Algorithm/LeetCode 2025. 4. 7. 09:43
✅ Problemhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ ✅ Approach & Solution방식) greedy 사용더보기조건최대 1개의 주식만 가지고 있을 수 있다.같은 날에 주식을 사고 팔 수 있다.최대 수익을 내려면 현재 값이 이전 값보다 큰 경우 무조건 팔아야 한다.class Solution { public int maxProfit(int[] prices) { int maxProfit = 0; for (int i = 1; i prices[i-1]) { maxProfit += (prices[i] - prices[i-1]); ..
-
[array] maximum product subarrayAlgorithm/LeetCode 2025. 4. 6. 12:11
✅ Problemhttps://leetcode.com/problems/maximum-product-subarray/description/ ✅ Approach & Solution방식)더보기부분 배열 원소들의 최대 곱 구하기플로우현재 위치에서의 Max, Min을 구한다.subarray 이어야 하므로 연속된 값이 필요하여 현재 위치에서의 Max, Min을 따로 계산함 음수 값에 따라 결과가 달라지기 때문에 Min 값도 트래킹해야 함 (이전까지 음수였고 그 다음 값이 음수이면 곱했을 때 양수가 되는 경우)for문으로 Max, Min을 업데이트한다.Global Max를 구한다. (정답값)class Solution { public int maxProduct(int[] nums) { int max ..
-
[array] 3sum closestAlgorithm/LeetCode 2025. 4. 5. 12:28
✅ Problemhttps://leetcode.com/problems/3sum-closest/description/ ✅ Approach & Solution방식) 정렬 후 투 포인터 사용더보기3개를 찾아야 할 때 : 1개는 고정해두고 나머지 2개를 찾자나머지 2개 찾을 때 투 포인터 사용정렬 필수 (배열의 인덱스 값 활용하지 않기 때문에 정렬 가능)class Solution { public int threeSumClosest(int[] nums, int target) { int result = 0; // 반환할 세 수의 합 int minDiff = Integer.MAX_VALUE; // target과 세 수의 합의 최소 차이 int left, right, sum;..
-
[array] container with most waterAlgorithm/LeetCode 2025. 3. 22. 14:39
✅ Problemhttps://leetcode.com/problems/container-with-most-water/description ✅ Approach & Solution방식)더보기투 포인터 사용포인터 이동 시 한칸 씩 이동할 필요없음, 최소 height보다 클 때까지 이동시킴결과값이 커지려면 minHeight 값이 커져야 함 (right - left 는 포인터 이동할 때마다 무조건 작아지는 값이니까)class Solution { public int maxArea(int[] height) { int maxArea = 0; int left = 0; int right = height.length - 1; while (left