diff --git a/daejik/Week_10/Boj12886.java b/daejik/Week_10/Boj12886.java new file mode 100644 index 0000000..73a4447 --- /dev/null +++ b/daejik/Week_10/Boj12886.java @@ -0,0 +1,112 @@ +package Week10; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Boj12886 { + static Queue queue = new LinkedList(); + static boolean[][] visited = new boolean[3][1501]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int cntFirstGroup = Integer.parseInt(st.nextToken()); + int cntSecondGroup = Integer.parseInt(st.nextToken()); + int cntThirdGroup = Integer.parseInt(st.nextToken()); + + visited[0][cntFirstGroup] = true; + visited[1][cntSecondGroup] = true; + visited[2][cntThirdGroup] = true; + + queue.add(new Stones(cntFirstGroup, cntSecondGroup, cntThirdGroup)); + + while(!queue.isEmpty()) { + Stones now = queue.poll(); + + if(sameNumAll(now)) { + System.out.println("1"); + return; + } + + + if(now.aGroup != now.bGroup) { + Stones next = now; + + if(now.aGroup > now.bGroup) { + next.aGroup -= next.bGroup; + next.bGroup += next.bGroup; + } else { + next.bGroup -= next.aGroup; + next.aGroup += next.aGroup; + } + + if(isNotNegative(next) == true && isVisited(next) == false) { + queue.add(next); + } + } + + if(now.aGroup != now.cGroup) { + Stones next = now; + + if(now.aGroup > now.cGroup) { + next.aGroup -= next.cGroup; + next.cGroup += next.cGroup; + } else { + next.cGroup -= next.aGroup; + next.aGroup += next.aGroup; + } + + if(isNotNegative(next) == true && isVisited(next) == false) { + queue.add(next); + } + } + + if(now.bGroup != now.cGroup) { + Stones next = now; + + if(now.bGroup > now.cGroup) { + next.bGroup -= next.cGroup; + next.cGroup += next.cGroup; + } else { + next.cGroup -= next.bGroup; + next.bGroup += next.bGroup; + } + + if(isNotNegative(next) == true && isVisited(next) == false) { + queue.add(next); + } + } + } + System.out.println("0"); + + } + public static boolean isNotNegative(Stones stones) { + if(stones.aGroup >= 0 && stones.bGroup >= 0 && stones.cGroup >= 0) return true; + return false; + } + public static boolean sameNumAll(Stones stones) { + if(stones.aGroup == stones.bGroup && stones.aGroup == stones.cGroup && stones.bGroup == stones.cGroup) return true; + return false; + } + public static boolean isVisited(Stones stones) { + if(visited[0][stones.aGroup] == true && visited[1][stones.bGroup] == true && visited[2][stones.cGroup] == true) return true; + visited[0][stones.aGroup] = true; + visited[1][stones.bGroup] = true; + visited[2][stones.cGroup] = true; + return false; + } + +} +class Stones{ + int aGroup, bGroup, cGroup; + + Stones(int aGroup, int bGroup, int cGroup){ + this.aGroup = aGroup; + this.bGroup = bGroup; + this.cGroup = cGroup; + } +} diff --git a/daejik/Week_10/Boj16929.java b/daejik/Week_10/Boj16929.java new file mode 100644 index 0000000..415c795 --- /dev/null +++ b/daejik/Week_10/Boj16929.java @@ -0,0 +1,67 @@ +package Week10; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Boj16929 { + static char[][] map = new char[50][50]; + static boolean[][] visited = new boolean[50][50]; + static int dr[]= {1, 0, -1, 0}, dc[]= {0, 1, 0, -1}; + static int numRow, numCol; + static boolean flag; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + numRow = Integer.parseInt(st.nextToken()); + numCol = Integer.parseInt(st.nextToken()); + + for(int row = 0; row < numRow; row++) { + map[row] = br.readLine().toCharArray(); + } + + for(int row = 0; row < numRow; row++) { + for(int col = 0; col < numCol; col++) { + + visited[row][col] = true; + dfs(row, col, row, col, 1); + visited[row][col] = false; + + if(flag == true) { + System.out.println("Yes"); + return; + } + } + } + System.out.println("No"); + } + public static void dfs(int nowR, int nowC, int originR, int originC, int cnt) { + if(flag == true) return; + + for(int direction=0; direction<4; direction++) { + int nextR = nowR + dr[direction]; + int nextC = nowC + dc[direction]; + + if(!canNext(nextR, nextC)) continue; + if(visited[nextR][nextC]) { + if(nextR == originR && nextC == originC && cnt >= 3) { + flag = true; + return; + } + } else { + if(map[nextR][nextC] == map[originR][originC]) { + visited[nextR][nextC] = true; + dfs(nextR, nextC, originR, originC, cnt + 1); + visited[nextR][nextC] = false; + } + } + } + } + public static boolean canNext(int r, int c) { + if(r<0 || c<0 || r>=numRow || c>=numCol) return false; + return true; + } +} diff --git a/daejik/Week_10/Leet2078.java b/daejik/Week_10/Leet2078.java new file mode 100644 index 0000000..35cfc1e --- /dev/null +++ b/daejik/Week_10/Leet2078.java @@ -0,0 +1,5 @@ +package Week10; + +public class Leet2078 { + +} diff --git a/daejik/Week_11/leetcode797.java b/daejik/Week_11/leetcode797.java new file mode 100644 index 0000000..676892a --- /dev/null +++ b/daejik/Week_11/leetcode797.java @@ -0,0 +1,40 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +class Solution { + List visitInform = new ArrayList(); + List> ans = new ArrayList<>(); + int[][] graphInform; + + public List> allPathsSourceTarget(int[][] graph) { + visitInform.add(0); + graphInform = graph; + dfs(0); + + return ans; + } + + public void dfs(int idx) { + + if(idx == graphInform.length - 1){ + // , + List tmp = new ArrayList<>(); + tmp.addAll(visitInform); + ans.add(tmp); + + return; + } + + if(graphInform[idx].length > 0){ + // 湮 + for(int i=0; i visitInform = new ArrayList(); + List> ans = new ArrayList<>(); + int[][] graphInform; + + public List> allPathsSourceTarget(int[][] graph) { + visitInform.add(0); + graphInform = graph; + dfs(0); + + return ans; + } + + public void dfs(int idx) { + + if(idx == graphInform.length - 1){ + // , + List tmp = new ArrayList<>(); + tmp.addAll(visitInform); + ans.add(tmp); + + return; + } + + if(graphInform[idx].length > 0){ + // 湮 + for(int i=0; i= nums.length){ + toIndex = 0; + } + } + } +} \ No newline at end of file diff --git a/daejik/Week_15/leetcode2295.java b/daejik/Week_15/leetcode2295.java new file mode 100644 index 0000000..5aca8a8 --- /dev/null +++ b/daejik/Week_15/leetcode2295.java @@ -0,0 +1,21 @@ +class Solution { + int[] indexArray = new int[1000001]; + + public int[] arrayChange(int[] nums, int[][] operations) { + for(int i=0; i 0) { + dp[i] = Math.max(dp[i - 1], dp[i]); + } + } + int sum = 0; + for (int i : worker) { + sum += dp[i]; + } + return sum; + } +} \ No newline at end of file diff --git a/daejik/Week_16/leetcode826_sort.java b/daejik/Week_16/leetcode826_sort.java new file mode 100644 index 0000000..ff3ca19 --- /dev/null +++ b/daejik/Week_16/leetcode826_sort.java @@ -0,0 +1,17 @@ +class Solution { + + public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { + List> jobs = new ArrayList<>(); + int N = profit.length, res = 0, i = 0, best = 0; + for (int j = 0; j < N; ++j) + jobs.add(new Pair(difficulty[j], profit[j])); + Collections.sort(jobs, Comparator.comparing(Pair::getKey)); + Arrays.sort(worker); + for (int ability : worker) { + while (i < N && ability >= jobs.get(i).getKey()) + best = Math.max(jobs.get(i++).getValue(), best); + res += best; + } + return res; + } +} \ No newline at end of file diff --git a/daejik/Week_17/leetcode2008.java b/daejik/Week_17/leetcode2008.java new file mode 100644 index 0000000..1517293 --- /dev/null +++ b/daejik/Week_17/leetcode2008.java @@ -0,0 +1,24 @@ +class Solution { + + + public long maxTaxiEarnings(int n, int[][] A) { + long[] dp = new long[n + 1]; + Arrays.sort(A, (a, b) -> a[0] - b[0]); + int j = 0; + + for(int i = 1; i <= n; i++) { + dp[i] = Math.max(dp[i], dp[i - 1]); + + while (j < A.length && A[j][0] == i) { + int startPoint = A[j][0]; + int endPoint = A[j][1]; + int tip = A[j][2]; + + + dp[endPoint] = Math.max(dp[endPoint], dp[i] + (endPoint - startPoint + tip)); + j++; + } + } + return dp[n]; + } +} \ No newline at end of file diff --git a/daejik/Week_17/leetcode349.java b/daejik/Week_17/leetcode349.java new file mode 100644 index 0000000..c9f6e68 --- /dev/null +++ b/daejik/Week_17/leetcode349.java @@ -0,0 +1,33 @@ +class Solution { + + HashSet set = new HashSet(); + + public int[] intersection(int[] nums1, int[] nums2) { + if(nums1.length < nums2.length){ + for(int i=0; i> ans; + List tmp = new ArrayList<>(); + + public List> combine(int n, int k) { + ans = new ArrayList<>(); + + dfs(1, n, 0, k); + + return ans; + } + + public void dfs(int pickedIdx, int limitIdx, int pickedNum, int limitNum){ + + if(pickedNum == limitNum){ + ans.add(new ArrayList<>(tmp)); + return; + } + + for(int i=pickedIdx; i<=limitIdx; i++){ + tmp.add(i); + dfs(i + 1, limitIdx, pickedNum + 1, limitNum); + tmp.remove(tmp.size() - 1); + } + } +} \ No newline at end of file diff --git a/daejik/Week_20/leetcode40.java b/daejik/Week_20/leetcode40.java new file mode 100644 index 0000000..e71e4ae --- /dev/null +++ b/daejik/Week_20/leetcode40.java @@ -0,0 +1,30 @@ +class Solution { + + List> ans = new ArrayList<>(); + List tmpMemory = new ArrayList<>(); + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + + dfs(0, 0, candidates, target); + + return ans; + } + + public void dfs(int idx, int sum, int[] candidates, int target){ + + if(sum == target){ + + ans.add(new ArrayList<>(tmpMemory)); + return; + } + + for(int i=idx; i target) continue; + if(i > idx && candidates[i] == candidates[i-1]) continue; + tmpMemory.add(candidates[i]); + dfs(i + 1, sum + candidates[i], candidates, target); + tmpMemory.remove(tmpMemory.size() - 1); + } + } +} \ No newline at end of file diff --git a/daejik/Week_20/leetcode890.java b/daejik/Week_20/leetcode890.java new file mode 100644 index 0000000..8e36649 --- /dev/null +++ b/daejik/Week_20/leetcode890.java @@ -0,0 +1,35 @@ +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List answer = new ArrayList<>(); + + for(String str : words){ + + HashMap mapFromPattern = new HashMap<>(); + HashMap mapFromWords = new HashMap<>(); + boolean flag = true; + + for(int i=0; i 0 && sum == targetMemo){ + tmpAns++; + + if(tmpAns > ans) ans = tmpAns; + + sum = 0; + } + + if(idx >= nums.length) return; + + + dfs(nums, idx + 1, sum + nums[idx], tmpAns); + + sum = 0; + dfs(nums, idx + 1, sum, tmpAns); + + } +} \ No newline at end of file diff --git a/daejik/Week_21/leetcode1662.java b/daejik/Week_21/leetcode1662.java new file mode 100644 index 0000000..c699038 --- /dev/null +++ b/daejik/Week_21/leetcode1662.java @@ -0,0 +1,14 @@ +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + String word1Sum = ""; + String word2Sum = ""; + + for(int i=0; i 1){ + + if(s.charAt(s.length() - 1) == '1') { + // '0' idx ã + int idx = s.lastIndexOf('0'); + + String zeroStr = ""; + + if(idx < 0){ + for(int i=0; i> i) & 1) == 1) one++; + else zero++; + } + + ans += one * zero; + } + + return ans; + } +} \ No newline at end of file diff --git a/daejik/Week_27/leetcode1160.java b/daejik/Week_27/leetcode1160.java new file mode 100644 index 0000000..2f1a875 --- /dev/null +++ b/daejik/Week_27/leetcode1160.java @@ -0,0 +1,28 @@ +class Solution { + public int countCharacters(String[] words, String chars) { + int[] charsCnt = new int['z' - 'a' + 1]; + int ans = 0; + + for(int i=0; i= charsCnt[idx]){ + flag = false; + break; + } + tmpCnt[idx]++; + } + + if(flag == true) ans += nowWord.length(); + } + + return ans; + } +} \ No newline at end of file diff --git a/daejik/Week_27/leetcode901.java b/daejik/Week_27/leetcode901.java new file mode 100644 index 0000000..7d39dac --- /dev/null +++ b/daejik/Week_27/leetcode901.java @@ -0,0 +1,19 @@ +class StockSpanner { + // <, > + Stack stack; + + public StockSpanner() { + stack = new Stack<>(); + } + + public int next(int price) { + int ans = 1; + + while(!stack.isEmpty() && stack.peek()[0] <= price){ + ans += stack.pop()[1]; + } + stack.push(new int[]{price, ans}); + + return ans; + } +} \ No newline at end of file diff --git a/daejik/Week_30/leetcode1233.java b/daejik/Week_30/leetcode1233.java new file mode 100644 index 0000000..c809ceb --- /dev/null +++ b/daejik/Week_30/leetcode1233.java @@ -0,0 +1,27 @@ +class Solution { + public List removeSubfolders(String[] folder) { + Arrays.sort(folder, Comparator.comparing(s -> s.length())); + Set seen = new HashSet<>(); + + for(String str : folder){ + boolean isInside = false; + int slashIndex = 1; + + while((slashIndex = str.indexOf("/", slashIndex)) > 0){ + String tempStr = str.substring(0, slashIndex); + + if(seen.contains(tempStr) == true){ + isInside = true; + break; + } + slashIndex++; + } + + if(isInside == false){ + seen.add(str); + } + } + + return new ArrayList<>(seen); + } +} \ No newline at end of file diff --git a/daejik/Week_30/leetcode2225.java b/daejik/Week_30/leetcode2225.java new file mode 100644 index 0000000..9572bf1 --- /dev/null +++ b/daejik/Week_30/leetcode2225.java @@ -0,0 +1,43 @@ +class Solution { + public List> findWinners(int[][] matches) { + Set zeroLossSet = new HashSet<>(); + Set oneLossSet = new HashSet<>(); + Set theOthersSet = new HashSet<>(); + + for (int[] match : matches) { + int winner = match[0]; + int loser = match[1]; + + // (1) ¸ ó + if (!oneLossSet.contains(winner) && !theOthersSet.contains(winner)) { + zeroLossSet.add(winner); + } + + // (2) Loser ó + if (zeroLossSet.contains(loser)) { + // ѹ -> 1 + zeroLossSet.remove(loser); + oneLossSet.add(loser); + } else if (oneLossSet.contains(loser)) { + // ѹ -> 2 ̻ + oneLossSet.remove(loser); + theOthersSet.add(loser); + } else if (theOthersSet.contains(loser)) { + // 2 ̻ ̹ -> ƹ ó ʿ + continue; + } else { + // 𿡵 -> ѹ + oneLossSet.add(loser); + } + } + + // + List> answer = Arrays.asList(new ArrayList<>(), new ArrayList<>()); + answer.get(0).addAll(zeroLossSet); + answer.get(1).addAll(oneLossSet); + Collections.sort(answer.get(0)); + Collections.sort(answer.get(1)); + + return answer; + } +} \ No newline at end of file diff --git a/daejik/Week_31/leetcode1465.java b/daejik/Week_31/leetcode1465.java new file mode 100644 index 0000000..de17c59 --- /dev/null +++ b/daejik/Week_31/leetcode1465.java @@ -0,0 +1,19 @@ +class Solution { + public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + Arrays.sort(horizontalCuts); + Arrays.sort(verticalCuts); + + int max_h = horizontalCuts[0]; + int max_v = verticalCuts[0]; + + for (int i = 0; i < horizontalCuts.length - 1; i++) + max_h = Math.max(max_h, horizontalCuts[i + 1] - horizontalCuts[i]); + for (int i = 0; i < verticalCuts.length - 1; i++) + max_v = Math.max(max_v, verticalCuts[i + 1] - verticalCuts[i]); + + max_h = Math.max(max_h, h - horizontalCuts[horizontalCuts.length - 1]); + max_v = Math.max(max_v, w - verticalCuts[verticalCuts.length - 1]); + + return (int)((long)max_h * max_v % 1000000007); + } +} \ No newline at end of file diff --git a/daejik/Week_31/leetcode2437.java b/daejik/Week_31/leetcode2437.java new file mode 100644 index 0000000..bc71395 --- /dev/null +++ b/daejik/Week_31/leetcode2437.java @@ -0,0 +1,33 @@ +class Solution { + public int countTime(String time) { + int ans = 1; + + if(time.charAt(4) == '?') { + ans *= 10; + } + if(time.charAt(3) == '?'){ + ans *= 6; + } + + if(time.charAt(0) == '?' && time.charAt(1) == '?'){ + ans *= 24; + } else { + if(time.charAt(0) == '?'){ + if(time.charAt(1) < '4') { + ans *= 3; + } else { + ans *= 2; + } + } + if(time.charAt(1) == '?'){ + if(time.charAt(0) == '2'){ + ans *= 4; + } else { + ans *= 10; + } + } + } + + return ans; + } +} \ No newline at end of file diff --git a/daejik/Week_34/leetcode1865.java b/daejik/Week_34/leetcode1865.java new file mode 100644 index 0000000..16bfd0a --- /dev/null +++ b/daejik/Week_34/leetcode1865.java @@ -0,0 +1,37 @@ +class FindSumPairs { + int[] nums1, nums2; + Map map = new HashMap(); // key: num2, value: key + + public FindSumPairs(int[] nums1, int[] nums2) { + this.nums1 = nums1.clone(); + this.nums2 = nums2.clone(); + + for(int num2 : nums2){ + map.put(num2, map.getOrDefault(num2, 0) + 1); + } + } + + public void add(int index, int val) { + map.put(nums2[index], map.getOrDefault(nums2[index], 0) - 1); + nums2[index] += val; + map.put(nums2[index], map.getOrDefault(nums2[index], 0) + 1); + } + + public int count(int tot) { + int cnt = 0; + + for(int num1 : nums1){ + if(map.containsKey(tot - num1)){ + cnt += map.get(tot - num1); + } + } + return cnt; + } +} + +/** + * Your FindSumPairs object will be instantiated and called as such: + * FindSumPairs obj = new FindSumPairs(nums1, nums2); + * obj.add(index,val); + * int param_2 = obj.count(tot); + */ \ No newline at end of file diff --git a/daejik/Week_34/leetcode20.java b/daejik/Week_34/leetcode20.java new file mode 100644 index 0000000..f8791f8 --- /dev/null +++ b/daejik/Week_34/leetcode20.java @@ -0,0 +1,39 @@ +class Solution { + public boolean isValid(String s) { + int strLen = s.length(); + Stack stack = new Stack<>(); + + for(String i : s.split("")){ + + if(i.equals("(") || i.equals("{") || i.equals("[")){ + stack.push(i); + } else { + if(stack.empty()){ + return false; + } + } + + if(i.equals(")")){ + if(!"(".equals(stack.peek())){ + return false; + } + stack.pop(); + } else if(i.equals("}")){ + if(!"{".equals(stack.peek())){ + return false; + } + stack.pop(); + } else if(i.equals("]")){ + if(!"[".equals(stack.peek())){ + return false; + } + stack.pop(); + } + } + if(stack.size() == 0){ + return true; + } else { + return false; + } + } +} \ No newline at end of file diff --git a/daejik/Week_35/leetcode2353.java b/daejik/Week_35/leetcode2353.java new file mode 100644 index 0000000..214f84d --- /dev/null +++ b/daejik/Week_35/leetcode2353.java @@ -0,0 +1,64 @@ +class FoodRatings { + + HashMap> highestRatingFoodInCuisine = new HashMap<>(); + HashMap foodToCuisine = new HashMap<>(); + HashMap foodToRaiting = new HashMap<>(); + + public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { + int n = foods.length; + + for(int i=0; i foodOfThisCuisine = highestRatingFoodInCuisine.getOrDefault(cuisine, + new TreeSet ((a,b)-> + foodToRaiting.get(a).equals(foodToRaiting.get(b)) ? a.compareTo(b) : foodToRaiting.get(b)-foodToRaiting.get(a))); + // Both comparators are equal + /* new Comparator(){ + @Override + public int compare(String a, String b){ + int aRat = foodToRat.get(a); + int bRat = foodToRat.get(b); + + if(aRat != bRat) return bRat - aRat; // largest rating first + for(int i = 0; i < Math.min(a.length(), b.length()); i++){ + if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i); + } + return a.length() - b.length(); + } + }) + */ + + foodOfThisCuisine.add(food); + highestRatingFoodInCuisine.put(cuisine, foodOfThisCuisine); + } + } + + // CompareTo() is used to compare whether 2 strings are equal in hashSet! + // So remove, change value of key in HashMap, then insert again + public void changeRating(String food, int newRating) { + String cuisine = foodToCuisine.get(food); + foodToRaiting.put(food, newRating); + + TreeSet foodOfThisCuisine = highestRatingFoodInCuisine.get(cuisine); + foodOfThisCuisine.remove(food); + foodOfThisCuisine.add(food); + highestRatingFoodInCuisine.put(cuisine, foodOfThisCuisine); + } + + public String highestRated(String cuisine) { + return highestRatingFoodInCuisine.get(cuisine).first(); + } +} + +/** + * Your FoodRatings object will be instantiated and called as such: + * FoodRatings obj = new FoodRatings(foods, cuisines, ratings); + * obj.changeRating(food,newRating); + * String param_2 = obj.highestRated(cuisine); + */ \ No newline at end of file diff --git a/daejik/Week_36/leetcode1642.java b/daejik/Week_36/leetcode1642.java new file mode 100644 index 0000000..a1b8cfa --- /dev/null +++ b/daejik/Week_36/leetcode1642.java @@ -0,0 +1,16 @@ +class Solution { + PriorityQueue pq = new PriorityQueue<>(); + + public int furthestBuilding(int[] heights, int bricks, int ladders) { + for (int i = 0; i < heights.length - 1; i++) { + int diff = heights[i + 1] - heights[i]; + if (diff > 0) + pq.add(d); + if (pq.size() > ladders) + bricks -= pq.poll(); + if (bricks < 0) + return i; + } + return heights.length - 1; + } +} \ No newline at end of file diff --git a/daejik/Week_36/leetcode659.java b/daejik/Week_36/leetcode659.java new file mode 100644 index 0000000..3c2412c --- /dev/null +++ b/daejik/Week_36/leetcode659.java @@ -0,0 +1,28 @@ +class Solution { + public boolean isPossible(int[] nums) { + Map ready = new HashMap<>(); + Map end = new HashMap<>(); + + for(int num : nums){ + ready.put(num, ready.getOrDefault(num, 0) + 1); + } + + for(int num : nums){ + if(ready.get(num) == 0) continue; + ready.put(num, ready.get(num) - 1); + + if(end.containsKey(num - 1) && end.get(num - 1) > 0){ + end.put(num - 1, end.get(num - 1) - 1); + end.put(num, end.getOrDefault(num, 0) + 1); + } else if(ready.containsKey(num + 1) && ready.containsKey(num + 2) + && ready.get(num + 1) > 0 && ready.get(num + 2) > 0){ + ready.put(num + 1, ready.get(num + 1) - 1); + ready.put(num + 2, ready.get(num + 2) - 1); + end.put(num + 2, end.getOrDefault(num + 2, 0) + 1); + } else { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git "a/daejik/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" "b/daejik/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" new file mode 100644 index 0000000..a0e408c --- /dev/null +++ "b/daejik/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" @@ -0,0 +1,52 @@ +class Solution { + // d -> l -> r -> u + int[] dr = {1, 0, 0, -1}; + int[] dc = {0, -1, 1, 0}; + String[] word = {"d", "l", "r", "u"}; + int maxR = 0, maxC = 0; + int goalR = 0, goalC = 0; + String tmpAnswer = ""; + + public boolean dfs(int r, int c, int k, String str, int diff){ + + if(diff > k) return false; + if(k == 0 && diff == 0){ + tmpAnswer = str; + return true; + } + for(int d=0; d<4; d++){ + int nr = r + dr[d]; + int nc = c + dc[d]; + + if(nr >= 0 && nc >= 0 && nr < maxR && nc < maxC){ + if((diff % 2 == 0 && k % 2 == 0) || (diff % 2 == 1 && k % 2 == 1)){ + + if(dfs(nr, nc, k - 1, str + word[d], Math.abs(nr - goalR) + Math.abs(nc - goalC))){ + return true; + } + } + } + } + return false; + } + + public String solution(int n, int m, int x, int y, int r, int c, int k) { + String answer; + maxR = n; + maxC = m; + goalR = r - 1; + goalC = c - 1; + + int diff = Math.abs((r - 1) - (x - 1)) + Math.abs((c - 1) - (y - 1)); + + dfs(x - 1, y - 1, k, "", diff); + + answer = tmpAnswer; + + if(answer.equals("")){ + answer = "impossible"; + } + + return answer; + } +} \ No newline at end of file diff --git "a/daejik/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" "b/daejik/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" new file mode 100644 index 0000000..283c501 --- /dev/null +++ "b/daejik/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" @@ -0,0 +1,20 @@ +class Solution { + public long solution(int cap, int n, int[] deliveries, int[] pickups) { + long answer = 0; + int deliver = 0, pickup = 0; + + for(int i=n-1; i>=0; i--){ + int cnt = 0; + + while(deliver < deliveries[i] || pickup < pickups[i]){ + cnt++; + deliver += cap; + pickup += cap; + } + deliver -= deliveries[i]; + pickup -= pickups[i]; + answer += (i + 1) * cnt * 2; + } + return answer; + } +} \ No newline at end of file diff --git a/daejik/Week_8/Boj21924.java b/daejik/Week_8/Boj21924.java new file mode 100644 index 0000000..d93c842 --- /dev/null +++ b/daejik/Week_8/Boj21924.java @@ -0,0 +1,128 @@ +package Week8; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Boj21924 { + private static int[] parent; + private static boolean[] visitedNode; + private static ArrayList> graph; + private static ArrayList vector; + private static Queue q; + private static int N, M; + private static long totalCost, ans; + + public static void main(String[] args) throws IOException{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + + parent = new int[N + 1]; + visitedNode = new boolean[N + 1]; + vector = new ArrayList<>(); + q = new LinkedList(); + graph = new ArrayList<>(); + + for(int i=0; i<=N; i++) { + graph.add(new ArrayList()); + } + + for(int m=0; m{ + int a, b, cost; + + Struct(int a, int b, int cost){ + this.a = a; + this.b = b; + this.cost = cost; + } + + @Override + public int compareTo(Struct o) { + if(o.cost > cost) return -1; + else if(o.cost < cost) return 1; + else return 0; + } + + @Override + public String toString() { + return "(" + this.a + "," + this.b + "):"+ this.cost; + } +} diff --git a/daejik/Week_8/Boj22252.java b/daejik/Week_8/Boj22252.java new file mode 100644 index 0000000..6e086c6 --- /dev/null +++ b/daejik/Week_8/Boj22252.java @@ -0,0 +1,71 @@ +package Week8; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.StringTokenizer; + +public class Boj22252 { + private static HashMap hashMap = new HashMap<>(); + private static ArrayList> arr = new ArrayList<>(); + private static int Q, gorilCnt; + private static long ans; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + Q = Integer.parseInt(br.readLine()); + + while(Q-- > 0) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int type = Integer.parseInt(st.nextToken()); + String name = st.nextToken(); + + String nameValue = hashMap.get(name); + int arrIdx = 0; + + // name - arrε + if(nameValue == null) { + arr.add(new ArrayList()); + arrIdx = gorilCnt; + hashMap.put(name, String.valueOf(arrIdx)); + gorilCnt++; + } + else { + arrIdx = Integer.parseInt(nameValue); + } + + // + if(type == 1) { + inputData(st, arrIdx); + } + // 󿡼 + else { + ans += (long)getData(st, arrIdx); + } + } + System.out.println(ans); + } + public static void inputData(StringTokenizer st, int idx) { + int inputNum = Integer.parseInt(st.nextToken()); + + for(int i=0; i 0 && !arr.get(idx).isEmpty()) { + ret += (int)arr.get(idx).get(0); + arr.get(idx).remove(0); + } + return ret; + } + +} diff --git a/daejik/Week_8/Boj3584.java b/daejik/Week_8/Boj3584.java new file mode 100644 index 0000000..4775705 --- /dev/null +++ b/daejik/Week_8/Boj3584.java @@ -0,0 +1,62 @@ +package Week8; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Boj3584 { + public static Queue q = new LinkedList(); + public static int T, N; + public static int[] visited = new int[100001]; + public static int[] parent = new int[100001]; + + public static void main(String[] args) throws IOException{ + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = null; + T = Integer.parseInt(br.readLine()); + + while(T-- > 0) { + Arrays.fill(visited, 0); + Arrays.fill(parent, 0); + while(!q.isEmpty()) q.poll(); + + N = Integer.parseInt(br.readLine()); + + for(int n=1; n= 1) { + System.out.println(parentNode); + break; + } + else if(visited[parentNode] == 0){ + visited[parentNode]++; + q.add(parentNode); + } + } + } + } +} diff --git a/daejik/Week_9/Boj10775.java b/daejik/Week_9/Boj10775.java new file mode 100644 index 0000000..abf8c58 --- /dev/null +++ b/daejik/Week_9/Boj10775.java @@ -0,0 +1,34 @@ +package Week9; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Boj10775 { + static int[] parent; + static int numGates, numPlanes, ans; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + numGates = Integer.parseInt(br.readLine()); + numPlanes = Integer.parseInt(br.readLine()); + parent = new int[numGates + 1]; + + for(int i=1; i<=numGates; i++) parent[i] = i; + + for(int i=0; i> ingredientsMap = new HashMap<>(); + static ArrayList[] ingredientArrayList; + + public static void main(String[] args) throws IOException{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + totalTestCase = Integer.parseInt(br.readLine()); + + while(totalTestCase-- > 0) { + StringTokenizer st = new StringTokenizer(br.readLine()); + numOfIngredients = Integer.parseInt(st.nextToken()); + money = Integer.parseInt(st.nextToken()); + + inputIngredientsInfo(br, st); + moveFromMapToList(); + resultOfSimulation = 0; + simulation(0, money, Integer.MAX_VALUE); + System.out.println(resultOfSimulation); + } + } + public static void moveFromMapToList(){ + ingredientArrayList = new ArrayList[ingredientsMap.size()]; + int idx = 0; + for(String type : ingredientsMap.keySet()) { + ingredientArrayList[idx] = ingredientsMap.get(type); + idx++; + } + } + public static void simulation(int idx, int testMoney, int testQuality) { + if(idx >= ingredientArrayList.length) { + if(resultOfSimulation < testQuality) resultOfSimulation = testQuality; + return; + } + + for(int i=0; i < ingredientArrayList[idx].size(); i++) { + if(testMoney >= ingredientArrayList[idx].get(i).price) { + if(testQuality > ingredientArrayList[idx].get(i).quality) + simulation(idx + 1, testMoney - ingredientArrayList[idx].get(i).price, ingredientArrayList[idx].get(i).quality); + else + simulation(idx + 1, testMoney - ingredientArrayList[idx].get(i).price, testQuality); + } + } + } + public static void inputIngredientsInfo(BufferedReader br, StringTokenizer st) throws IOException { + ingredientsMap.clear(); + + while(numOfIngredients-- > 0) { + st = new StringTokenizer(br.readLine()); + + String type = st.nextToken(); + String name = st.nextToken(); + Integer price = Integer.parseInt(st.nextToken()); + Integer quality = Integer.parseInt(st.nextToken()); + + IngredientsClass ingredientsClass = new IngredientsClass(price, quality); + + ArrayList arrayListOfIngredients = ingredientsMap.get(type); + + if(arrayListOfIngredients == null) { + arrayListOfIngredients = new ArrayList<>(); + } + arrayListOfIngredients.add(ingredientsClass); + + ingredientsMap.put(type, arrayListOfIngredients); + } + } +} +class IngredientsClass{ + int price, quality; + + IngredientsClass(int price, int quality){ + this.price = price; + this.quality = quality; + } + + @Override + public String toString() { + return "price:"+this.price+", quality:"+this.quality; + } +} \ No newline at end of file diff --git a/daejik/Week_9/leetcode1855.java b/daejik/Week_9/leetcode1855.java new file mode 100644 index 0000000..be9eebb --- /dev/null +++ b/daejik/Week_9/leetcode1855.java @@ -0,0 +1,24 @@ +package Week9; + + +class Solution{ + + public int maxDistance(int[] nums1, int[] nums2) { + int maxDist = 0; + int nums1Length = nums1.length; + int nums2Length = nums2.length; + + for(int i=0; i maxDist) maxDist = tmpDist; + } + if(maxDist > 0) return maxDist - 1; + return 0; + } +} diff --git a/hyejin/Week_10/Two Dots.java b/hyejin/Week_10/Two Dots.java new file mode 100644 index 0000000..3f88f27 --- /dev/null +++ b/hyejin/Week_10/Two Dots.java @@ -0,0 +1,101 @@ +package boj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BOJ_16929 { + + static int N, M; + static boolean findCycle = false; + static char[][] map; + static boolean[][] visited; + static int[] dy = { -1, 1, 0, 0 }; // 상하좌우 + static int[] dx = { 0, 0, -1, 1 }; + static class Dot { + int y; + int x; + Dot(int y, int x) { + this.y = y; + this.x = x; + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer stk = new StringTokenizer(br.readLine()); + + N = Integer.parseInt(stk.nextToken()); + M = Integer.parseInt(stk.nextToken()); + map = new char[N][M]; + visited = new boolean[N][M]; + + for(int i=0; i list = new ArrayList<>(); + list.add(start); + dfs(start, list); + } + } + + System.out.println(findCycle ? "Yes" : "No"); + } + + public static void dfs(Dot now, ArrayList list) { + visited[now.y][now.x] = true; + // 기저 : 사이클 찾음 + if(findCycle) + return; + + // 기저 : 사이클 형성 조건 + int size = list.size(); + if(size >= 4 && size % 2 == 0) { + if(isAdjacent(list.get(0), list.get(size-1))) { + findCycle = true; + return; + } + } + + // 상하좌우 탐색 + for(int i=0; i= N || nx < 0 || nx >= M) + return false; + return true; + } + + public static boolean isAdjacent(Dot d1, Dot d2) { + // 좌우로 인접 + if((Math.abs(d1.x - d2.x) == 1) && (d1.y - d2.y == 0)) + return true; + // 상하로 인접 + else if((Math.abs(d1.y - d2.y) == 1) && (d1.x - d2.x == 0)) + return true; + + return false; + } +} diff --git a/hyejin/Week_10/Two Furthest Houses With Different Colors.java b/hyejin/Week_10/Two Furthest Houses With Different Colors.java new file mode 100644 index 0000000..eebd62b --- /dev/null +++ b/hyejin/Week_10/Two Furthest Houses With Different Colors.java @@ -0,0 +1,26 @@ +package leetcode; + +public class LeetCode_2078 { + + public static int solution(int[] colors) { + int max = 0; + + for(int std=0; std set = new HashSet<>(); + for(int i=0; i abSum = getABSum(set); + HashSet dSet = getDSet(set, abSum); + + int result = 0; + for(int d : dSet) { + result = Math.max(result, d); + } + + System.out.println(result); + } + + public static HashSet getABSum(HashSet set) { + // a+b 모든 경우의 수 + HashSet ret = new HashSet<>(); + + for(int a : set) { + for(int b : set) { + ret.add(a + b); + } + } + + return ret; + } + + public static HashSet getDSet(HashSet set, HashSet abSum) { + // d-c == a+b 인 모든 d를 저장 + HashSet dSet = new HashSet<>(); + + for(int d : set) { + for(int c : set) { + if(abSum.contains(d-c)) { + dSet.add(d); + } + } + } + + return dSet; + } +} diff --git a/hyejin/Week_11/Minimum Number of Swaps to Make the Binary String Alternating.java b/hyejin/Week_11/Minimum Number of Swaps to Make the Binary String Alternating.java new file mode 100644 index 0000000..22ce161 --- /dev/null +++ b/hyejin/Week_11/Minimum Number of Swaps to Make the Binary String Alternating.java @@ -0,0 +1,75 @@ +class Solution { + public int minSwaps(String s) { + // 1과 0의 갯수 세서 저장해두기 + int[] count = new int[2]; + + for(int i=0; i= 2) { + return -1; + } + + // alternating 하게 만들 수 있는 경우 + // swap 개수 구하는 방법 + // alternating한 문자열과 다른 글자의 수 / 2 + + String alternating = ""; + + // 더 갯수가 많은 숫자로 시작할 수 밖에 없다 + if(count[0] > count[1]) { + alternating = "01"; + alternating = generateAlternating(alternating, s); + } + else if(count[0] < count[1]) { + alternating = "10"; + alternating = generateAlternating(alternating, s); + } + // 같으면 어떡하지? + else if(count[0] == count[1]) { + alternating = ""; + String alt0 = generateAlternating("01", s); + String alt1 = generateAlternating("10", s); + + int result0 = countDifference(s, alt0); + int result1 = countDifference(s, alt1); + + return Math.min(result0, result1); + } + + int result = countDifference(s, alternating); + return result; + } + + public String generateAlternating(String alternating, String s) { + while(alternating.length() < s.length()) { + if(alternating.charAt(alternating.length()-1) == '1') { + alternating += "01"; + } + if(alternating.charAt(alternating.length()-1) == '0') { + alternating += "10"; + } + } + + if(alternating.length() > s.length()) { + alternating = alternating.substring(0, alternating.length()-1); + } + + return alternating; + } + + public int countDifference(String s, String alternating) { + int result = 0; + for(int i=0; i indegrees = new HashMap<>(); + static HashMap lineage = new HashMap<>(); + static HashMap> graph = new HashMap<>(); + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer stk = new StringTokenizer(br.readLine()); + + N = Integer.parseInt(stk.nextToken()); + M = Integer.parseInt(stk.nextToken()); + + // 건국한 사람 + String root = br.readLine(); + indegrees.put(root, 0); + + for(int i=0; i childrenOfParent1 = graph.getOrDefault(parent1, new ArrayList<>()); + ArrayList childrenOfParent2 = graph.getOrDefault(parent2, new ArrayList<>()); + childrenOfParent1.add(child); + childrenOfParent2.add(child); + + graph.put(parent1, childrenOfParent1); + graph.put(parent2, childrenOfParent2); + } + lineage.put(root, 1.0); + + ArrayList candidates = new ArrayList<>(); + for(int i=0; i candidates) { + Queue queue = new LinkedList<>(); + + // indegree 0인 사람을 Queue에 담는다 + Set keySet = indegrees.keySet(); + for (String name : keySet) { + if(indegrees.get(name) == 0) { + queue.offer(name); + } + } + + while (!queue.isEmpty()) { + // 큐에서 사람 하나 꺼냄 + String now = queue.poll(); + + // 그 사람의 자식을 꺼내서 인디그리 감소시킴 + for(String child : graph.getOrDefault(now, new ArrayList<>())) { + int indegree = indegrees.get(child); + indegree--; + indegrees.put(child, indegree); + + double blood = lineage.get(child); + blood += lineage.get(now); + lineage.put(child, blood); + + // 0되면 큐에 다시 넣음 + if(indegree == 0) { + queue.offer(child); + + double lineageValue = lineage.get(child); + lineageValue /= 2; + lineage.put(child, lineageValue); + } + } + } + + double blood = 0; + String selected = null; + for (String candidate : candidates) { + double currentBloodValue = lineage.getOrDefault(candidate, 0.0); + if(blood < currentBloodValue) { + blood = currentBloodValue; + selected = candidate; + } + } + + System.out.println(selected); + } +} diff --git a/hyejin/Week_12/All Paths From Source to Target.java b/hyejin/Week_12/All Paths From Source to Target.java new file mode 100644 index 0000000..9ba9806 --- /dev/null +++ b/hyejin/Week_12/All Paths From Source to Target.java @@ -0,0 +1,35 @@ +class Solution { + int index = 0; + boolean[] visited = new boolean[15]; + + public List> allPathsSourceTarget(int[][] graph) { + ArrayList> result = new ArrayList<>(); + + dfs(graph, 0, new ArrayList<>(), result); + + return result; + } + + public void dfs(int[][] graph, int cur, ArrayList history, ArrayList> result) { + + // 기저 : 도착 + if(cur == graph.length-1) { + List path = (ArrayList) history.clone(); + path.add(0, 0); + result.add(path); + return; + } + + for(int i=0; i0) + return true; + } + + HashMap hashMap = new HashMap<>(); // mod, index + for (int i = 0; i < prefixSum.length; i++) { + int mod = prefixSum[i]%k; + if(mod == 0 && i>0) { + return true; + } + else if(hashMap.containsKey(mod)) { + int size = i - hashMap.get(mod); + if(size >= 2) + return true; + } + else + hashMap.put(mod, i); + } + + return false; + } +} \ No newline at end of file diff --git a/hyejin/Week_13/Previous Permutation With One Swap.java b/hyejin/Week_13/Previous Permutation With One Swap.java new file mode 100644 index 0000000..ebd042c --- /dev/null +++ b/hyejin/Week_13/Previous Permutation With One Swap.java @@ -0,0 +1,30 @@ +class Solution { + public int[] prevPermOpt1(int[] arr) { + // 뒤에서부터 탐색하며, 처음으로 증가하는 부분 인덱스 구하기 + int index = arr.length-1; + for(int i=arr.length-1; i>0; i--) { + if(arr[i-1] > arr[i]) { + index = i-1; + break; + } + } + + // 뒤에서부터 index 바로 뒤까지 탐색 -> arr[index]보다 작은 값과 swap + for(int i=arr.length-1; i>index; i--) { + if(arr[i] < arr[index] && arr[i] != arr[i-1]) { + arr = swap(arr, i, index); + break; + } + } + return arr; + } + + public int[] swap(int[] arr, int index1, int index2) { + int temp = arr[index2]; + arr[index2] = arr[index1]; + arr[index1] = temp; + + return arr; + } + +} \ No newline at end of file diff --git a/hyejin/Week_13/Swap for Longest Repeated Character Substring.java b/hyejin/Week_13/Swap for Longest Repeated Character Substring.java new file mode 100644 index 0000000..6a04caa --- /dev/null +++ b/hyejin/Week_13/Swap for Longest Repeated Character Substring.java @@ -0,0 +1,105 @@ +class Solution { + public int maxRepOpt1(String text) { + char[] textArr = text.toCharArray(); + + // char grouping + ArrayList groups = new ArrayList<>(); + char cur; + char prev = textArr[0]; + int startPosition = 0; + int endPosition = 0; + + for(int i=1; i= 0) { + for(int i=0; i<=leftIndex; i++) { + if(textArr[i] == target) + return true; + } + } + + // right range check + if(rightIndex < textArr.length) { + for(int i=rightIndex; i stack = new Stack<>(); + + for(int i=0; i temperatures[i]) { + result[i] = count; + count = 0; + break; + } + else + count++; + + } + } + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_14/Linked List Cycle.java b/hyejin/Week_14/Linked List Cycle.java new file mode 100644 index 0000000..41e50f2 --- /dev/null +++ b/hyejin/Week_14/Linked List Cycle.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + HashSet history = new HashSet<>(); + + if(head == null) + return false; + + ListNode curNode = head; + + while(curNode.next != null) { + ListNode next = curNode.next; + + if(history.contains(next)) + return true; + else { + history.add(next); + curNode = next; + } + } + return false; + } +} \ No newline at end of file diff --git a/hyejin/Week_15/Replace Elements in an Array.java b/hyejin/Week_15/Replace Elements in an Array.java new file mode 100644 index 0000000..64103fa --- /dev/null +++ b/hyejin/Week_15/Replace Elements in an Array.java @@ -0,0 +1,30 @@ +class Solution { + public int[] arrayChange(int[] nums, int[][] operations) { + + HashMap indexMap = saveIndex(nums); + + // {1, 3} -> 1을 3으로 변경 + for(int i=0; i saveIndex(int[] nums) { + HashMap ret = new HashMap(); + + for(int index=0; index= nums.length) + newIndex -= nums.length; + nums[newIndex] = copy[curIndex]; + } + } +} \ No newline at end of file diff --git a/hyejin/Week_16/Most Profit Assigning Work (n^2).java b/hyejin/Week_16/Most Profit Assigning Work (n^2).java new file mode 100644 index 0000000..e69de29 diff --git a/hyejin/Week_17/Intersection of Two Arrays.java b/hyejin/Week_17/Intersection of Two Arrays.java new file mode 100644 index 0000000..399e882 --- /dev/null +++ b/hyejin/Week_17/Intersection of Two Arrays.java @@ -0,0 +1,22 @@ +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + boolean[] checkExistingNumber1 = new boolean[1001]; + boolean[] checkExistingNumber2 = new boolean[1001]; + + for (int i = 0; i < nums1.length; i++) { + checkExistingNumber1[nums1[i]] = true; + } + + for (int i = 0; i < nums2.length; i++) { + checkExistingNumber2[nums2[i]] = true; + } + + HashSet set = new HashSet<>(); + for(int i=0; i i).toArray(); + } +} \ No newline at end of file diff --git a/hyejin/Week_17/Maximum Earnings From Taxi.java b/hyejin/Week_17/Maximum Earnings From Taxi.java new file mode 100644 index 0000000..c9d09f7 --- /dev/null +++ b/hyejin/Week_17/Maximum Earnings From Taxi.java @@ -0,0 +1,28 @@ +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (r1, r2) -> r1[0] - r2[0]); + + long[] dp = new long[n + 1]; // dp[n] : n까지 운행했을 때 최대 수입 + + int j = 0; + for (int i = 1; i <= n; i++) { + // dp[i] = Math.max(dp[i - 1], dp[i]); + dp[i] = dp[i-1]; + while (j < rides.length) { + int start = rides[j][0]; + int end = rides[j][1]; + int tip = rides[j][2]; + int profit = end - start + tip; + + if (start != i) + break; + + dp[end] = Math.max(dp[end], dp[start] + profit); + j++; + } + } + + return dp[n]; + + } +} diff --git a/hyejin/Week_18/Maximum Twin Sum of A Linked List.java b/hyejin/Week_18/Maximum Twin Sum of A Linked List.java new file mode 100644 index 0000000..9bb8f36 --- /dev/null +++ b/hyejin/Week_18/Maximum Twin Sum of A Linked List.java @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + int index = 0; + int[] values = new int[100001]; + ListNode curNode = head; + + while (curNode != null) { + values[index++] = curNode.val; + curNode = curNode.next; + } + + // index == size of ListNode + int maxSum = 0; + // twin인 두 인덱스의 합은 index-1 일 것이에요 + for (int i = 0; i <= (index - 1) / 2; i++) { + int twin1 = i; + int twin2 = index-1-i; + + maxSum = Math.max(maxSum, values[twin1]+values[twin2]); + } + + return maxSum; + } +} \ No newline at end of file diff --git a/hyejin/Week_18/Valid Triangle Number.java b/hyejin/Week_18/Valid Triangle Number.java new file mode 100644 index 0000000..6eb317c --- /dev/null +++ b/hyejin/Week_18/Valid Triangle Number.java @@ -0,0 +1,32 @@ +class Solution { + public int triangleNumber(int[] nums) { + /* + * 삼각형 변이 a, b, c 일 때 c가 가장 긴 변이라면 a + b > c 가 성립한다. + */ + int count = 0; + + // 오름차순 정렬 + Arrays.sort(nums); + + // 가장 긴 변 고정으로 두고 + for (int maxIndex = nums.length - 1; maxIndex > 1; maxIndex--) { + int left = 0; + int right = maxIndex - 1; + + while (left < right) { + // left, right가 조건을 만족한다면 + // left는 left ~ right 사이의 값을 가질 수 있다. + if (nums[left] + nums[right] > nums[maxIndex]) { + count += right - left; // 경우의 수 + right--; + } + // 만족하지 않는다면 늘려봐야지 + else { + left++; + } + } + } + + return count; + } +} \ No newline at end of file diff --git a/hyejin/Week_19/Combinations.java b/hyejin/Week_19/Combinations.java new file mode 100644 index 0000000..4053500 --- /dev/null +++ b/hyejin/Week_19/Combinations.java @@ -0,0 +1,26 @@ +class Solution { + public ListListInteger combine(int n, int k) { + ListListInteger ret = new ArrayListListInteger(); + boolean[] check = new boolean[n + 1]; + + dfs(ret, new ArrayList(), n, k, 1, 1); + + return ret; + } + + public void dfs(ListListInteger ret, ListInteger inner, int n, int k, int depth, int cur) { + 기저 k개 다 찼음 + if (depth k) { + ret.add(new ArrayListInteger(inner)); + return; + } + + cur보다 큰 숫자들 백트래킹 + for (int i = cur; i = n; i++) { + inner.add(i); + dfs(ret, inner, n, k, depth + 1, i + 1); + inner.remove(inner.size() - 1); + } + + } +} \ No newline at end of file diff --git "a/hyejin/Week_19/Ways to Split Array Into Three Subarray_\354\230\244\353\213\265.java" "b/hyejin/Week_19/Ways to Split Array Into Three Subarray_\354\230\244\353\213\265.java" new file mode 100644 index 0000000..a2f2973 --- /dev/null +++ "b/hyejin/Week_19/Ways to Split Array Into Three Subarray_\354\230\244\353\213\265.java" @@ -0,0 +1,57 @@ +class Solution { + public int waysToSplit(int[] nums) { + // 부분합 + int[] prefixSums = new int[nums.length]; + prefixSums[0] = nums[0]; + + for (int i = 1; i < nums.length; i++) { + prefixSums[i] = prefixSums[i - 1] + nums[i]; + } + int count = 0; + + // i: left, mid 구분 지점 + for (int i = 0; i < nums.length; i++) { + int leftSum = prefixSums[i]; + + int left = binarySearch(prefixSums, leftSum, i, i + 1, true); + int right = binarySearch(prefixSums, leftSum, i, i + 1, false); + if (left == -1 || right == -1) + continue; + + count += ((right - left + 1) % 1000000007); + } + + return count; + } + + public int binarySearch(int[] prefixSums, int leftSum, int left, int point, boolean searchingLeft) { + int l = left + 1; + int r = prefixSums.length - 1; + int res = -1; + + while (l <= r) { + int m = (l + r) / 2; + + // 0 ~ left : left + // left+1 ~ m : mid + // m+1 ~ end : right + int midSum = prefixSums[m] - leftSum; + int rightSum = prefixSums[prefixSums.length - 1] - prefixSums[m]; + + if (leftSum <= midSum && midSum <= rightSum) { + res = m; + if (searchingLeft) + r = m -1; + else + l = m + 1; + } else if (midSum < leftSum) { // + // midSum 늘려줌 + l = m + 1; + } else { + r = m -1; + } + } + + return res; + } +} \ No newline at end of file diff --git "a/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\204\261\352\263\265.java" "b/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\204\261\352\263\265.java" new file mode 100644 index 0000000..042f7ba --- /dev/null +++ "b/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\204\261\352\263\265.java" @@ -0,0 +1,58 @@ +class Solution { + public int waysToSplit(int[] nums) { + // 부분합 + int[] prefixSums = new int[nums.length]; + prefixSums[0] = nums[0]; + + for (int i = 1; i < nums.length; i++) { + prefixSums[i] = prefixSums[i - 1] + nums[i]; + } + int count = 0; + + // 1 2 | 2 2 5 0 + // i: left, mid 구분 지점 + for (int i = 0; i < nums.length; i++) { + int leftSum = prefixSums[i]; + + int left = binarySearch(prefixSums, leftSum, i, i + 1, true); + int right = binarySearch(prefixSums, leftSum, i, i + 1, false); + if (left == -1 || right == -1) + continue; + + count = (count % 1000000007) + ((right - left + 1) % 1000000007); + } + + return count; + } + + public int binarySearch(int[] prefixSums, int leftSum, int left, int point, boolean searchingLeft) { + int l = left + 1; + int r = prefixSums.length - 2; + int res = -1; + + while (l <= r) { + int m = (l + r) / 2; + + // 0 ~ left : left + // left+1 ~ m : mid + // m+1 ~ end : right + int midSum = prefixSums[m] - leftSum; + int rightSum = prefixSums[prefixSums.length - 1] - prefixSums[m]; + + if (leftSum <= midSum && midSum <= rightSum) { + res = m; + if (searchingLeft) + r = m -1; + else + l = m + 1; + } else if (midSum < leftSum) { // + // midSum 늘려줌 + l = m + 1; + } else { + r = m -1; + } + } + + return res; + } +} \ No newline at end of file diff --git "a/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\213\234\352\260\204\354\264\210\352\263\274.java" "b/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\213\234\352\260\204\354\264\210\352\263\274.java" new file mode 100644 index 0000000..572a8cb --- /dev/null +++ "b/hyejin/Week_19/Ways to Split Array Into Three Subarrays_\354\213\234\352\260\204\354\264\210\352\263\274.java" @@ -0,0 +1,34 @@ +class Solution { + public int waysToSplit(int[] nums) { + // 부분합 + int[] prefixSums = new int[nums.length]; + prefixSums[0] = nums[0]; + + for (int i = 1; i < nums.length; i++) { + prefixSums[i] = prefixSums[i - 1] + nums[i]; + } + + long count = 0; + + // i: left, mid 구분 지점 + for (int i = 0; i < nums.length; i++) { + int leftSum = prefixSums[i]; + + int point = i + 1; // mid, right 구분 지점 + while(point < nums.length-1) { + int midSum = prefixSums[point] - prefixSums[i]; + int rightSum = prefixSums[prefixSums.length-1] - prefixSums[point]; + + // 조건 만족 + if(leftSum <= midSum && midSum <= rightSum) { + count++; + } + + // 한칸씩 앞으로 가본다 + point++; + } + } + + return (int) count % 1000000007; + } +} \ No newline at end of file diff --git a/hyejin/Week_20/Combination Sum II.java b/hyejin/Week_20/Combination Sum II.java new file mode 100644 index 0000000..0945b53 --- /dev/null +++ b/hyejin/Week_20/Combination Sum II.java @@ -0,0 +1,38 @@ +class Solution { + public List> combinationSum2(int[] candidates, int target) { + List> result = new ArrayList>(); + Arrays.sort(candidates); + backTracking(result, new ArrayList<>(), candidates, 0, target, 0); + return result; + } + + public void backTracking(List> result, List combination, int[] candidates, int index, + int target, int sum) { + // 종료 1. 합계 target과 일치 + if (sum == target) { + // 중복 방지 + if (!result.contains(combination)) + result.add(new ArrayList(combination)); + return; + } + // 종료 2. 배열 끝까지 옴 + else if (index >= candidates.length) { + return; + } + // 종료 3. 합계 초과 + else if (sum > target) { + return; + } + + + combination.add(candidates[index]); + backTracking(result, combination, candidates, index + 1, target, sum + candidates[index]); + combination.remove(combination.size() - 1); + + while (index + 1 < candidates.length && candidates[index] == candidates[index+1]) + index++; + + backTracking(result, combination, candidates, index + 1, target, sum); + + } +} \ No newline at end of file diff --git "a/hyejin/Week_20/Combination Sum II_\354\213\234\352\260\204\354\264\210\352\263\274.java" "b/hyejin/Week_20/Combination Sum II_\354\213\234\352\260\204\354\264\210\352\263\274.java" new file mode 100644 index 0000000..b3be597 --- /dev/null +++ "b/hyejin/Week_20/Combination Sum II_\354\213\234\352\260\204\354\264\210\352\263\274.java" @@ -0,0 +1,39 @@ +class Solution { + public List> combinationSum2(int[] candidates, int target) { + List> result = new ArrayList>(); + backTracking(result, new ArrayList<>(), candidates, 0, target, 0); + return result; + } + + public void backTracking(List> result, List combination, int[] candidates, int index, + int target, int sum) { + // 종료 1. 합계 target과 일치 + if (sum == target) { + // 중복 방지 + ArrayList temp = new ArrayList<>(combination); + Collections.sort(temp); + if (!result.contains(temp)) + result.add(new ArrayList(temp)); + return; + } + // 종료 2. 배열 끝까지 옴 + else if (index >= candidates.length) { + return; + } + // 종료 3. 합계 초과 + else if (sum > target) { + return; + } + + + // 새로운 합계가 target을 넘지 않을 경우 진행 + if (target >= sum + candidates[index]) { + combination.add(candidates[index]); + backTracking(result, combination, candidates, index + 1, target, sum + candidates[index]); + combination.remove(combination.size() - 1); + } + + backTracking(result, combination, candidates, index + 1, target, sum); + + } +} \ No newline at end of file diff --git a/hyejin/Week_20/Find and Replace Pattern.java b/hyejin/Week_20/Find and Replace Pattern.java new file mode 100644 index 0000000..3bbc551 --- /dev/null +++ b/hyejin/Week_20/Find and Replace Pattern.java @@ -0,0 +1,48 @@ +class Solution { + public List findAndReplacePattern(String[] words, String pattern) { + List result = new ArrayList<>(); + + for (int i = 0; i < words.length; i++) { + String word = words[i]; + + // 길이 다르면 탈락 + if (word.length() != pattern.length()) + continue; + + // 한글자씩 대응시킴 + HashMap map = new HashMap<>(); // + boolean[] isPatternOccupied = new boolean[26]; + boolean flag = true; + + for (int j = 0; j < word.length(); j++) { + char wordLetter = word.charAt(j); + char patternLetter = pattern.charAt(j); + + // wordLetter와 매핑된 글자 존재 + if (map.containsKey(wordLetter)) { + // 매핑된 글자와 패턴이 불일치 + if (map.get(wordLetter) != patternLetter) { + flag = false; + break; + } + } + // 매핑된 글자 없는 경우, 해당 패턴도 사용되지 않음 -> 할당 + else if (!isPatternOccupied[patternLetter - 'a']) { + map.put(wordLetter, patternLetter); + isPatternOccupied[patternLetter - 'a'] = true; + } + // 매핑된 글자 없는데, 패턴은 이미 사용되어서 매핑 불가 -> 불가능 + else { + flag = false; + } + + } + + if (flag) { + result.add(word); + } + } + + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_21/Check If Two String Arrays are Equivalent.java b/hyejin/Week_21/Check If Two String Arrays are Equivalent.java new file mode 100644 index 0000000..a9d3456 --- /dev/null +++ b/hyejin/Week_21/Check If Two String Arrays are Equivalent.java @@ -0,0 +1,15 @@ +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + StringBuilder concat1 = new StringBuilder(); + StringBuilder concat2 = new StringBuilder(); + + for(int i=0; i map = new HashMap<>(); // <누적sum, 나온 횟수> + map.put(0, 0); + int sum = 0; + int result = 0; + + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + + // 이전에 sum - target이 저장되었었는데 + // 지금 또 나왔다는 것은 + // 이 사이의 합이 target 과 같다는 것. + if (map.containsKey(sum - target)) { + result = Math.max(result, map.get(sum - target) + 1); + } + map.put(sum, result); + } + + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_22/Matchsticks to Square.java b/hyejin/Week_22/Matchsticks to Square.java new file mode 100644 index 0000000..4d877b8 --- /dev/null +++ b/hyejin/Week_22/Matchsticks to Square.java @@ -0,0 +1,69 @@ +class Solution { + static final int TOP = 0; + static final int BOTTOM = 1; + static final int LEFT = 2; + static final int RIGHT = 3; + + public boolean makesquare(int[] matchsticks) { + // 성냥이 4개 미만인 경우 + if (matchsticks.length < 4) + return false; + + // 정사각형이므로 모든 성냥 길이의 합이 4로 나누어 떨어져야 함 + int sum = 0; + for (int length : matchsticks) { + sum += length; + } + if (sum % 4 != 0) + return false; + + Arrays.sort(matchsticks); + return dfs(matchsticks, new int[4], matchsticks.length-1, sum / 4); + } + + public boolean dfs(int[] matchsticks, int[] sums, int index, int target) { + // 정사각형 만들어짐 + if (sums[TOP] == target && sums[BOTTOM] == target && sums[LEFT] == target && sums[RIGHT] == target) + return true; + + // 한 변이라도 target보다 크면 더이상 진행 X + if (sums[TOP] > target || sums[BOTTOM] > target || sums[LEFT] > target || sums[RIGHT] > target) + return false; + + int matchstick = matchsticks[index]; + + // 1. top에 놓아보기 + int temp = sums[TOP]; + sums[TOP] += matchstick; + boolean top = dfs(matchsticks, sums, index - 1, target); + sums[TOP] = temp; + if (top) + return true; + + // 2. bottom에 놓아보기 + temp = sums[BOTTOM]; + sums[BOTTOM] += matchstick; + boolean bottom = dfs(matchsticks, sums, index - 1, target); + sums[BOTTOM] = temp; + if (bottom) + return true; + + // 3. left에 놓아보기 + temp = sums[LEFT]; + sums[LEFT] += matchstick; + boolean left = dfs(matchsticks, sums, index - 1, target); + sums[LEFT] = temp; + if (left) + return true; + + // 4. right에 놓아보기 + temp = sums[RIGHT]; + sums[RIGHT] += matchstick; + boolean right = dfs(matchsticks, sums, index - 1, target); + sums[RIGHT] = temp; + if (right) + return true; + + return false; + } +} \ No newline at end of file diff --git a/hyejin/Week_22/Maximum XOR After Operations.java b/hyejin/Week_22/Maximum XOR After Operations.java new file mode 100644 index 0000000..cd3defa --- /dev/null +++ b/hyejin/Week_22/Maximum XOR After Operations.java @@ -0,0 +1,9 @@ +class Solution { + public int maximumXOR(int[] nums) { + int result = 0; + for (int num : nums) + result |= num; + + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_23/Delete the Middle Node of a Linked List.java b/hyejin/Week_23/Delete the Middle Node of a Linked List.java new file mode 100644 index 0000000..a18ced9 --- /dev/null +++ b/hyejin/Week_23/Delete the Middle Node of a Linked List.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteMiddle(ListNode head) { + if (head == null || head.next == null) + return null; + + int count = 1; + ListNode cur = head; + while(cur.next != null) { + count++; + cur = cur.next; + } + + int middle = count / 2; + cur = head; + for(int i=0; i= left && num <= right) { + sum += (++plus); + minus = 0; + } + else if (num > right) { + plus = 0; + minus = 0; + } + } + + return sum; + } +} \ No newline at end of file diff --git a/hyejin/Week_24/Sum of Mutated Array Closest to Target.java b/hyejin/Week_24/Sum of Mutated Array Closest to Target.java new file mode 100644 index 0000000..c59e406 --- /dev/null +++ b/hyejin/Week_24/Sum of Mutated Array Closest to Target.java @@ -0,0 +1,50 @@ +class Solution { + public int findBestValue(int[] arr, int target) { + Arrays.sort(arr); + int result = arr[arr.length-1]; + int left = 0; + int right = arr[arr.length - 1]; + int minDiff = Integer.MAX_VALUE; + + while (left <= right) { + int mid = (left + right) / 2; + int sum = getSum(arr, mid); + int diff = Math.abs(target - sum); + + if (diff < minDiff) { + minDiff = diff; + result = mid; + } + else if (diff == minDiff) { + result = Math.min(result, mid); + } + + // target보다 작음 + if (sum < target) { + left = mid + 1; + } + else if (sum == target) { + result = mid; + break; + } + // target보다 큼 + else { + right = mid - 1; + } + } + return result; + } + + public int getSum(int[] arr, int mid) { + int sum = 0; + for (int i = 0; i < arr.length; i++) { + if (arr[i] <= mid) { + sum += arr[i]; + } else { + sum += mid; + } + } + return sum; + } + +} \ No newline at end of file diff --git a/hyejin/Week_25/Number of Steps to Reduce a Number in Binary Representation to One.java b/hyejin/Week_25/Number of Steps to Reduce a Number in Binary Representation to One.java new file mode 100644 index 0000000..44cf698 --- /dev/null +++ b/hyejin/Week_25/Number of Steps to Reduce a Number in Binary Representation to One.java @@ -0,0 +1,22 @@ +import java.math.BigInteger; +class Solution { + public int numSteps(String s) { + int count = 0; + BigInteger number = new BigInteger(s, 2); + + while (!number.equals(BigInteger.ONE)) { + count++; + + // 짝수: 나누기 2 + if (number.and(BigInteger.ONE).equals(BigInteger.ZERO)) { + number = number.shiftRight(1); + } + // 홀수: 더하기 1 + else { + number = number.add(BigInteger.ONE); + } + + } + return count; + } +} \ No newline at end of file diff --git a/hyejin/Week_25/Rank Teams By Votes.java b/hyejin/Week_25/Rank Teams By Votes.java new file mode 100644 index 0000000..8703c42 --- /dev/null +++ b/hyejin/Week_25/Rank Teams By Votes.java @@ -0,0 +1,39 @@ +class Solution { + public String rankTeams(String[] votes) { + int[][] voteCount = new int[26][26]; // [알파벳][등수] + + for (String vote : votes) { + for (int i = 0; i < vote.length(); i++) { + char ch = vote.charAt(i); + voteCount[ch - 'A'][i]++; + } + } + + char[] result = votes[0].toCharArray(); + Character[] resultTemp = new Character[votes[0].length()]; + + // result - resultTemp 복사 + for(int i=0; i { + for (int i = 0; i < 26; i++) { + // 경합하지 않으면 내림차순 + if (voteCount[c1 - 'A'][i] != voteCount[c2 - 'A'][i]) { + return voteCount[c2 -'A'][i] - voteCount[c1-'A'][i]; + } + } + // 경합하면 알파벳순서 + return c1 - c2; + }); + + // resultTemp - result 복사 + for(int i=0; i> i) & 1); + } + + count += (one * (nums.length - one)); + } + // 모든 수를 두개씩 짝지어서 XOR한 결과의 비트 개수를 구하는 것이니까 + /* + * 0 1 0 0 + * 1 1 1 0 + * 0 0 1 0 + * ------- + * 2 2 2 0 => 6 + * + * n개의 정수 중 k개가 1을 가지고 있다면, + * n-k개는 0을 가지고 있다. + * 그래서 k*(n-k) 개의 XOR 쌍을 지을 수 있다. + * 이것들이 더해지면 total XOR의 개수가 되는 것이다. + * 그러므로 k개의 비트가 해밍거래에 기여한다. + * k * (n - k) + * */ + + return count; + + } +} \ No newline at end of file diff --git a/hyejin/Week_30/Find Players With Zero or One Losses.java b/hyejin/Week_30/Find Players With Zero or One Losses.java new file mode 100644 index 0000000..c29013d --- /dev/null +++ b/hyejin/Week_30/Find Players With Zero or One Losses.java @@ -0,0 +1,36 @@ +class Solution { + public List> findWinners(int[][] matches) { + List> result = new ArrayList<>(); + result.add(new ArrayList<>()); + result.add(new ArrayList<>()); + + HashSet persons = new HashSet<>(); + HashMap loserMap = new HashMap<>(); + + for (int[] match : matches) { + int winner = match[0]; + int loser = match[1]; + + persons.add(winner); + persons.add(loser); + + int loseCount = loserMap.getOrDefault(loser, 0); + loserMap.put(loser, ++loseCount); + } + + for (int person : persons) { + // 진 적 없음 + if (!loserMap.containsKey(person)) { + result.get(0).add(person); + } + // 1번만 짐 + else if (loserMap.get(person) == 1) { + result.get(1).add(person); + } + } + + Collections.sort(result.get(0)); + Collections.sort(result.get(1)); + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_30/Remove Sub-Folders from the FileSystem.java b/hyejin/Week_30/Remove Sub-Folders from the FileSystem.java new file mode 100644 index 0000000..c4b1761 --- /dev/null +++ b/hyejin/Week_30/Remove Sub-Folders from the FileSystem.java @@ -0,0 +1,16 @@ +class Solution { + public List removeSubfolders(String[] folder) { + Arrays.sort(folder); + ArrayList result = new ArrayList<>(); + + for (String path : folder) { + // 아무것도 안 들어있을 때나 + // 바로 이전 경로와 현재 경로가 서브 관계가 아닌 경우 + if (result.isEmpty() || !path.startsWith(result.get(result.size()-1) + "/")) { + result.add(path); + } + + } + return result; + } +} \ No newline at end of file diff --git a/hyejin/Week_31/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.java b/hyejin/Week_31/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.java new file mode 100644 index 0000000..bb1e3ec --- /dev/null +++ b/hyejin/Week_31/Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.java @@ -0,0 +1,28 @@ +class Solution { + final static int MOD = 1000000007; + public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { + // hCuts, vCuts 오름차순 정렬 + Arrays.sort(horizontalCuts); + Arrays.sort(verticalCuts); + + // h, v로 잘렸을 때 각각 최댓값 구하기 + int maxHorizon = horizontalCuts[0]; + int maxVertical = verticalCuts[0]; + + for (int i = 1; i < horizontalCuts.length; i++) { + int width = horizontalCuts[i] - horizontalCuts[i - 1]; + maxHorizon = Math.max(maxHorizon, width); + } + maxHorizon = Math.max(maxHorizon, h - horizontalCuts[horizontalCuts.length - 1]); + + for (int i = 1; i < verticalCuts.length; i++) { + int width = verticalCuts[i] - verticalCuts[i - 1]; + maxVertical = Math.max(maxVertical, width); + } + maxVertical = Math.max(maxVertical, w - verticalCuts[verticalCuts.length - 1]); + + // 넓이 + long maxArea = (long) maxHorizon * (long) maxVertical; + return (int) (maxArea % MOD); + } +} \ No newline at end of file diff --git a/hyejin/Week_31/Number of Valid Clock Times.java b/hyejin/Week_31/Number of Valid Clock Times.java new file mode 100644 index 0000000..f2196cc --- /dev/null +++ b/hyejin/Week_31/Number of Valid Clock Times.java @@ -0,0 +1,40 @@ +class Solution { + public int countTime(String time) { + int answer = 1; + + if (time.charAt(4) == '?') // 0~9 + answer *= 10; + + if (time.charAt(3) == '?') // 0~5 + answer *= 6; + + if (time.charAt(0) == '?' && time.charAt(1) == '?') { // 0~23 + answer *= 24; + } + // 시간 맨 앞자리에 따라 달라짐 + else if (time.charAt(1) == '?') { + switch (time.charAt(0)) { + case '0': // 0? + case '1': // 1? + answer *= 10; + break; + + case '2': // 2? + answer *= 4; + break; + } + } + + else if (time.charAt(0) == '?') { + // 시간 뒷자리가 4이상이면 앞에 0, 1 + if (time.charAt(1) - '0' >= 4) { + answer *= 2; + } + // 시간 뒷자리가 0, 1, 2, 3이면 상관없음 0~ + else + answer *= 3; + } + + return answer; + } +} \ No newline at end of file diff --git a/hyejin/Week_32/Coin Change II.java b/hyejin/Week_32/Coin Change II.java new file mode 100644 index 0000000..beb5119 --- /dev/null +++ b/hyejin/Week_32/Coin Change II.java @@ -0,0 +1,39 @@ +class Solution { + public int change(int amount, int[] coins) { + int[][] dp = new int[coins.length][amount+1]; + for (int[] row : dp) { + Arrays.fill(row, -1); + } + + return dfs(coins, 0, amount, dp); + } + + /* + * dp[i][j] + * 0~i번째 코인까지를 사용해서 */ + public int dfs(int[] coins, int index, int amount, int[][] dp) { + // 남은 금액이 없는 경우 + if (amount == 0) + return 1; + + // 마지막 코인 + if (index == coins.length) { + return 0; + } + + // 저장했던 값이 있다면 그걸 쓴다 + if (dp[index][amount] != -1) + return dp[index][amount]; + + // 이번 코인 스킵 + int answer = dfs(coins, index+1, amount, dp); + + // 아직 합계 금액 모자란다면 + if (amount >= coins[index]) + answer += dfs(coins, index, amount - coins[index], dp); // 이번 코인 사용 + + // 값 저장 + dp[index][amount] = answer; + return answer; + } +} \ No newline at end of file diff --git a/hyejin/Week_33/Integer Break.java b/hyejin/Week_33/Integer Break.java new file mode 100644 index 0000000..49483b0 --- /dev/null +++ b/hyejin/Week_33/Integer Break.java @@ -0,0 +1,29 @@ +class Solution { + public int integerBreak(int n) { + int[] dp = new int[n + 1]; + Arrays.fill(dp, -1); + dp[1] = 1; + + return dfs(dp, n); + } + + public int dfs(int[] dp, int cur) { + // 기저 + if (cur == 1) + return 1; + + // 저장한 값 있으면 사용 + if (dp[cur] != -1) + return dp[cur]; + + // 저장한 값 없으면 계산해서 저장 + for (int i = 1; i < cur; i++) { + // 현재 메모값 vs 현재상태에서 만들 수 있는 모든 경우의 수 + dp[cur] = Math.max(dp[cur], i * (cur - i)); + dp[cur] = Math.max(dp[cur], i * dfs(dp, cur - i)); + } + + System.out.println("dp[" + cur + "] : " + dp[cur]); + return dp[cur]; + } +} \ No newline at end of file diff --git a/hyejin/Week_34/Finding Pairs With a Certain Sum.java b/hyejin/Week_34/Finding Pairs With a Certain Sum.java new file mode 100644 index 0000000..bf11585 --- /dev/null +++ b/hyejin/Week_34/Finding Pairs With a Certain Sum.java @@ -0,0 +1,52 @@ +class FindSumPairs { + + int[] nums1; + int[] nums2; + HashMap map; // nums2의 원소가 각각 몇개 있는지 + + public FindSumPairs(int[] nums1, int[] nums2) { + this.nums1 = nums1; + this.nums2 = nums2; + map = new HashMap<>(); + + for (int num2 : nums2) { + int cnt = map.getOrDefault(num2, 0); + map.put(num2, ++cnt); + } + } + + public void add(int index, int val) { + // map 갱신 + // oldVal-- + int oldCnt = map.get(nums2[index]); + map.put(nums2[index], --oldCnt); + + nums2[index] += val; + + // newVal++ + int newCnt = map.getOrDefault(nums2[index], 0); + map.put(nums2[index], ++newCnt); + } + + public int count(int tot) { + int cnt = 0; + + for (int num1 : nums1) { + int need = tot - num1; + + // nums2가 need를 가지고 있는지? + if (map.containsKey(need)) { + cnt += map.get(need); + } + } + + return cnt; + } +} + +/** + * Your FindSumPairs object will be instantiated and called as such: + * FindSumPairs obj = new FindSumPairs(nums1, nums2); + * obj.add(index,val); + * int param_2 = obj.count(tot); + */ \ No newline at end of file diff --git a/hyejin/Week_34/Valid Parentheses.java b/hyejin/Week_34/Valid Parentheses.java new file mode 100644 index 0000000..e80e7cc --- /dev/null +++ b/hyejin/Week_34/Valid Parentheses.java @@ -0,0 +1,35 @@ +class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + + HashMap pairs = new HashMap<>(); + pairs.put(')', '('); + pairs.put(']', '['); + pairs.put('}', '{'); + + // 한 글자씩 + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + + // 열리는 괄호면 + if (ch == '(' || ch == '[' || ch == '{') + stack.push(ch); + // 닫히는 괄호라면 + else { + // 비어 있으면 실패 + if (stack.isEmpty()) + return false; + + // 맨 위 꺼냄 + char top = stack.pop(); + + // 맨위가 짝꿍이어야 함 + char pair = pairs.get(ch); + if (pair != top) + return false; + } + } + + return stack.isEmpty() ? true : false; + } +} \ No newline at end of file diff --git a/hyejin/Week_35/Food Ratings.java b/hyejin/Week_35/Food Ratings.java new file mode 100644 index 0000000..088a965 --- /dev/null +++ b/hyejin/Week_35/Food Ratings.java @@ -0,0 +1,55 @@ + +class FoodRatings { + static class Food { + String name; + String cuisine; + int rating; + + Food(String name, String cuisine, int rating) { + this.name = name; + this.cuisine = cuisine; + this.rating = rating; + } + } + + HashMap foodMap; + HashMap> cuisineMap; // 음식카테고리 : 음식들 + + public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { + foodMap = new HashMap<>(); + cuisineMap = new HashMap<>(); + + for (int i = 0; i < foods.length; i++) { + Food food = new Food(foods[i], cuisines[i], ratings[i]); + foodMap.put(foods[i], food); + PriorityQueue pq = cuisineMap.getOrDefault(cuisines[i], new PriorityQueue( + (a, b) -> a.rating == b.rating ? a.name.compareTo(b.name) : b.rating - a.rating)); + pq.add(food); + cuisineMap.put(cuisines[i], pq); + } + } + + public void changeRating(String food, int newRating) { + Food f = foodMap.get(food); + PriorityQueue pq = cuisineMap.get(f.cuisine); + + // pq에서 제거 + pq.remove(f); + + // 다시 넣기 + f.rating = newRating; + pq.add(f); + } + + public String highestRated(String cuisine) { + return cuisineMap.get(cuisine).peek().name; + } + +} + +/** + * Your FoodRatings object will be instantiated and called as such: + * FoodRatings obj = new FoodRatings(foods, cuisines, ratings); + * obj.changeRating(food,newRating); + * String param_2 = obj.highestRated(cuisine); + */ \ No newline at end of file diff --git a/hyejin/Week_35/Smallest Subsequence of Distinct Characters.java b/hyejin/Week_35/Smallest Subsequence of Distinct Characters.java new file mode 100644 index 0000000..7dedfe8 --- /dev/null +++ b/hyejin/Week_35/Smallest Subsequence of Distinct Characters.java @@ -0,0 +1,42 @@ + + + +class Solution { + public String smallestSubsequence(String s) { + int[] freq = new int[26]; + boolean[] used = new boolean[26]; + Stack stack = new Stack(); + + // 알파벳이 몇번 나왔는지 + for (char ch : s.toCharArray()) { + freq[ch - 'a']++; + } + + for (char ch : s.toCharArray()) { + // 빈도수 차감 -> 뒤에 ch라는 글자가 몇개 남았는지를 알기 위함 + freq[ch -'a']--; + + // 이미 사용했다면 필요없다 SKIP + if (used[ch - 'a']) + continue; + + // 스택 top이 나보다 사전순으로 뒤 이고 + // 스택 top이 뒤에 또 있으면 + while(!stack.isEmpty() && ch < stack.peek() && freq[stack.peek() - 'a'] > 0) { + // 나중에 넣어도 되는 상황이므로 + // 스택 top을 빼버린다. + used[stack.pop() - 'a'] = false; + } + + // 대신 내가 들어간다 + stack.push(ch); + used[ch - 'a'] = true; + } + + StringBuilder sb = new StringBuilder(); + while (!stack.isEmpty()) + sb.append(stack.pop()); + + return sb.reverse().toString(); + } +} \ No newline at end of file diff --git "a/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250).java" "b/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250).java" new file mode 100644 index 0000000..b664d89 --- /dev/null +++ "b/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250).java" @@ -0,0 +1,60 @@ +class Solution { + public int furthestBuilding(int[] heights, int bricks, int ladders) { + int[][] cache = new int[bricks + 1][ladders + 1]; + for (int[] row : cache) { + Arrays.fill(row, -1); + } + + return dp(cache, 0, 0, 0, heights, bricks, ladders); + + } + + // cache[usedBricks][usedLadders] : usedBricks개의 벽돌, usedLadders개의 사다리를 이용해서 + // 가장 멀리 갈 수 있는 빌딩의 인덱스 반환 + public int dp(int[][] cache, int cur, int usedBricks, int usedLadders, int[] heights, int remainBricks, + int remainLadders) { + // 기저 [더 이상 갈 수 없다] + // 기저 1. 현재 위치가 마지막 빌딩 + if (cur == heights.length - 1) { + return cur; + } + // 기저 2. 올라가야 하는데 벽돌/사다리 다 씀 + if (heights[cur+1] > heights[cur] && remainBricks == 0 && remainLadders == 0) { + return cur; + } + // 기저 3. 벽돌은 모자라고 사다리는 없음 + int neededBricks = heights[cur + 1] - heights[cur]; + if (neededBricks > remainBricks && remainLadders == 0) { + return cur; + } + + // 캐시 있으면 반환 + if (cache[usedBricks][usedLadders] != -1) + return cache[usedBricks][usedLadders]; + + // 캐시 없으면 계산 + + // Case 1 : 벽돌, 사다리 안 써도 됨 + if (heights[cur] >= heights[cur + 1]) { + cache[usedBricks][usedLadders] = dp(cache, cur + 1, usedBricks, usedLadders, heights, remainBricks, + remainLadders); + return cache[usedBricks][usedLadders]; + } + + // Case 2 : 벽돌을 쓰는 경우 + int brickCase = Integer.MIN_VALUE; + int need = heights[cur + 1] - heights[cur]; + if (remainBricks > need) { + brickCase = dp(cache, cur + 1, usedBricks + need, usedLadders, heights, remainBricks - need, remainLadders); + } + // Case 3 : 사다리를 쓰는 경우 + int ladderCase = Integer.MIN_VALUE; + if (remainLadders > 0) + ladderCase = dp(cache, cur + 1, usedBricks, usedLadders + 1, heights, remainBricks, remainLadders - 1); + + // Case 2, 3중 큰 값으로 사용 + cache[usedBricks][usedLadders] = Math.max(brickCase, ladderCase); + + return cache[usedBricks][usedLadders]; + } +} \ No newline at end of file diff --git "a/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250)java" "b/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250)java" new file mode 100644 index 0000000..b664d89 --- /dev/null +++ "b/hyejin/Week_36/Furthest Building You Can Reach. (DP\354\213\244\355\214\250)java" @@ -0,0 +1,60 @@ +class Solution { + public int furthestBuilding(int[] heights, int bricks, int ladders) { + int[][] cache = new int[bricks + 1][ladders + 1]; + for (int[] row : cache) { + Arrays.fill(row, -1); + } + + return dp(cache, 0, 0, 0, heights, bricks, ladders); + + } + + // cache[usedBricks][usedLadders] : usedBricks개의 벽돌, usedLadders개의 사다리를 이용해서 + // 가장 멀리 갈 수 있는 빌딩의 인덱스 반환 + public int dp(int[][] cache, int cur, int usedBricks, int usedLadders, int[] heights, int remainBricks, + int remainLadders) { + // 기저 [더 이상 갈 수 없다] + // 기저 1. 현재 위치가 마지막 빌딩 + if (cur == heights.length - 1) { + return cur; + } + // 기저 2. 올라가야 하는데 벽돌/사다리 다 씀 + if (heights[cur+1] > heights[cur] && remainBricks == 0 && remainLadders == 0) { + return cur; + } + // 기저 3. 벽돌은 모자라고 사다리는 없음 + int neededBricks = heights[cur + 1] - heights[cur]; + if (neededBricks > remainBricks && remainLadders == 0) { + return cur; + } + + // 캐시 있으면 반환 + if (cache[usedBricks][usedLadders] != -1) + return cache[usedBricks][usedLadders]; + + // 캐시 없으면 계산 + + // Case 1 : 벽돌, 사다리 안 써도 됨 + if (heights[cur] >= heights[cur + 1]) { + cache[usedBricks][usedLadders] = dp(cache, cur + 1, usedBricks, usedLadders, heights, remainBricks, + remainLadders); + return cache[usedBricks][usedLadders]; + } + + // Case 2 : 벽돌을 쓰는 경우 + int brickCase = Integer.MIN_VALUE; + int need = heights[cur + 1] - heights[cur]; + if (remainBricks > need) { + brickCase = dp(cache, cur + 1, usedBricks + need, usedLadders, heights, remainBricks - need, remainLadders); + } + // Case 3 : 사다리를 쓰는 경우 + int ladderCase = Integer.MIN_VALUE; + if (remainLadders > 0) + ladderCase = dp(cache, cur + 1, usedBricks, usedLadders + 1, heights, remainBricks, remainLadders - 1); + + // Case 2, 3중 큰 값으로 사용 + cache[usedBricks][usedLadders] = Math.max(brickCase, ladderCase); + + return cache[usedBricks][usedLadders]; + } +} \ No newline at end of file diff --git a/hyejin/Week_36/Split Array into consecutive Subsequences.java b/hyejin/Week_36/Split Array into consecutive Subsequences.java new file mode 100644 index 0000000..01f6527 --- /dev/null +++ b/hyejin/Week_36/Split Array into consecutive Subsequences.java @@ -0,0 +1,44 @@ +class Solution { + public boolean isPossible(int[] nums) { + if (nums.length < 3) + return false; + + HashMap freq = new HashMap<>(); // 숫자 개수 + HashMap need = new HashMap<>(); // 숫자 : 얘가 필요하다고 몇번 적혔는지 + for (int num : nums) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + + for (int number : nums) { + // 남아있지 않으면 넘어감 + if (freq.get(number) == 0) + continue; + + // 남아있으면 + // number가 필요했었는지 일단 확인 + else if (need.getOrDefault(number, 0) > 0) { + freq.put(number, freq.get(number) - 1); + need.put(number, need.get(number) - 1); + + // 이제 number 다음 숫자가 필요하다고 적어둠 + need.put(number + 1, need.getOrDefault(number + 1, 0) + 1); + } + + // number는 필요 없었으므로 새로운 그룹을 찾아야 함 + // number, number+1, number+2 묶음 만들 수 있는지 확인해보자.. + else if (freq.getOrDefault(number, 0) > 0 && freq.getOrDefault(number + 1, 0) > 0 + && freq.getOrDefault(number + 2, 0) > 0) { + freq.put(number, freq.getOrDefault(number, 0) - 1); + freq.put(number + 1, freq.getOrDefault(number + 1, 0) - 1); + freq.put(number + 2, freq.getOrDefault(number + 2, 0) - 1); + + // number+3 도 올 수 있으면 좋겠네 + need.put(number + 3, need.getOrDefault(number + 3, 0) + 1); + } + // number는 필요하지도 않았고, 새로운 그룹을 만들 수도 없음.. + else + return false; + } + return true; + } +} \ No newline at end of file diff --git "a/hyejin/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" "b/hyejin/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" new file mode 100644 index 0000000..5ec78d9 --- /dev/null +++ "b/hyejin/Week_37/\353\257\270\353\241\234 \355\203\210\354\266\234 \353\252\205\353\240\271\354\226\264.java" @@ -0,0 +1,63 @@ +class Solution { + static int[] dx = { 1, 0, 0, -1 }; // d, l, r, u + static int[] dy = { 0, -1, 1, 0 }; + static String[] letter = { "d", "l", "r", "u" }; + + String answer = ""; + int n, m; + int r, c; + + public String solution(int n, int m, int x, int y, int r, int c, int k) { + this.n = n; + this.m = m; + this.r = r; + this.c = c; + + // 목적지까지 남은 거리 + int diff = Math.abs(y - c) + Math.abs(x - r); + + if (diff % 2 != k % 2) + return "impossible"; + if (diff > k) + return "impossible"; + + dfs(x, y, k, "", diff); + + if (answer.equals("")) + answer = "impossible"; + + return answer; + } + + public boolean dfs(int x, int y, int k, String path, int diff) { + // 목적지에 도착했고, 이동거리 k인 경우 + if (k == 0 && diff == 0) { + answer = path; + return true; + } + + for (int i = 0; i < 4; i++) { + int ny = y + dy[i]; + int nx = x + dx[i]; + + // 범위 체크 + if (ny <= 0 || ny > m || nx <= 0 || nx > n) + continue; + + // 이동 가능 거리가 모자라면 SKIP + if (diff > k) + continue; + + // 목적지까지 남은 거리와, 남은 이동가능 거리의 홀짝이 맞아야 함 + if (diff % 2 == k % 2) { + int nextDiff = Math.abs(r - nx) + Math.abs(c - ny); + if (dfs(nx, ny, k - 1, path + letter[i], nextDiff)) { + return true; + } + } + + } + return false; + } + +} \ No newline at end of file diff --git "a/hyejin/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" "b/hyejin/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" new file mode 100644 index 0000000..1b6b093 --- /dev/null +++ "b/hyejin/Week_37/\355\203\235\353\260\260 \353\260\260\353\213\254\352\263\274 \354\210\230\352\261\260\355\225\230\352\270\260.java" @@ -0,0 +1,98 @@ +class Solution { + public long solution(int cap, int n, int[] deliveries, int[] pickups) { + + long answer = 0; + int deliver = 0; + int pickup = 0; + int size = cap; + + // 처음 배달할 곳 + deliver = getNextDeliver(n, deliveries); + + // 처음 픽업할 곳 + pickup = getNextPickup(n, pickups); + + while (true) { + if (deliver == -1 && pickup == -1) + break; + + answer += (Math.max(deliver, pickup) + 1) * 2; + + // 배달 + while (true) { + // 배달할 곳이 없음 + if (deliver == -1) + break; + // 실을 공간 없음 + if (size == 0) + break; + + // 현재 위치에 배달 가능 + if (size >= deliveries[deliver]) { + size -= deliveries[deliver]; // 적재가능 차감 + deliveries[deliver] = 0; + deliver--; + } else { + deliveries[deliver] -= size; + size = 0; + } + + // 다음 목적지 정하기 + if (size == 0) { + deliver = getNextDeliver(deliver+1, deliveries); + } + + } + + size = cap; + + // 픽업 + while (true) { + // 픽업할 곳이 없음 + if (pickup == -1) + break; + // 실을 공간 없음 + if (size == 0) + break; + + // 현재 위치에 픽업 가능 + if (size >= pickups[pickup]) { + size -= pickups[pickup]; // 픽업가능 차감 + pickups[pickup] = 0; + pickup--; + } else { + pickups[pickup] -= size; + size = 0; + } + + // 다음 목적지 정하기 + if (size == 0) { + pickup = getNextPickup(pickup+1, pickups); + } + + } + size = cap; + } + return answer; + } + + private int getNextDeliver(int start, int[] deliveries) { + for (int i = start - 1; i >= 0; i--) { + if (deliveries[i] != 0) { + return i; + } + } + + return -1; + } + + private int getNextPickup(int start, int[] pickups) { + for (int i = start - 1; i >= 0; i--) { + if (pickups[i] != 0) { + return i; + } + } + + return -1; + } +} \ No newline at end of file diff --git "a/hyejin/Week_38/\353\247\210\353\262\225\354\235\230 \354\227\230\353\246\254\353\262\240\354\235\264\355\204\260.java" "b/hyejin/Week_38/\353\247\210\353\262\225\354\235\230 \354\227\230\353\246\254\353\262\240\354\235\264\355\204\260.java" new file mode 100644 index 0000000..da27646 --- /dev/null +++ "b/hyejin/Week_38/\353\247\210\353\262\225\354\235\230 \354\227\230\353\246\254\353\262\240\354\235\264\355\204\260.java" @@ -0,0 +1,32 @@ +class Solution { + public int solution(int storey) { + int answer = 0; + + while (storey > 0) { + int digit = storey % 10; + storey /= 10; + + // 5인 경우, 앞자리 숫자가 5이상이면 올려주는 것이 유리함. + if (digit == 5) { + if (storey%10 >= 5) { + answer += (10 - digit); + storey++; + } + else { + answer += digit; + } + } + // 더하는 것이 이득 + else if (digit > 5) { + answer += (10 - digit); + storey++; + } + // 빼는 것이 이득 + else { + answer += digit; + } + + } + return answer; + } +} \ No newline at end of file diff --git "a/hyejin/Week_8/\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \352\263\265\355\206\265 \354\241\260\354\203\201.java" "b/hyejin/Week_8/\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \352\263\265\355\206\265 \354\241\260\354\203\201.java" new file mode 100644 index 0000000..0b6807b --- /dev/null +++ "b/hyejin/Week_8/\352\260\200\354\236\245 \352\260\200\352\271\214\354\232\264 \352\263\265\355\206\265 \354\241\260\354\203\201.java" @@ -0,0 +1,102 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BOJ_3584 { + + static int n; + static boolean[] isNotRoot; + static ArrayList[] adj; + static int[] parent; + static int[] depth; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer stk; + int t = Integer.parseInt(br.readLine()); + + for(int test=0; test(); + } + parent = new int[n+1]; + depth = new int[n+1]; + + for(int i=0; i dv) { + while(du > dv) { + u = parent[u]; + du--; + } + } + else if(du < dv) { + while(du < dv) { + v = parent[v]; + dv--; + } + } + + // 같은 depth 됨 + // 위로 올라가면서 공통 부모 찾기 + while(u != v) { + u = parent[u]; + v = parent[v]; + } + + return u; + } + + // depth, parent 저장 + public static void dfs(int d, int now, int p) { + depth[now] = d; + parent[now] = p; + + // 자식 타고 DFS + for(int next : adj[now]) { + if(next != p) { + dfs(d+1, next, now); + } + } + } + + public static int findRoot(int n, boolean[] isNotRoot) { + // 부모가 하나도 없는 것이 root + for(int i=1; i<=n; i++) { + if(!isNotRoot[i]) + return i; + } + return 0; + } +} diff --git "a/hyejin/Week_8/\352\263\265\354\236\245 \354\273\250\354\204\244\355\204\264\355\212\270 \355\230\270\354\204\235.java" "b/hyejin/Week_8/\352\263\265\354\236\245 \354\273\250\354\204\244\355\204\264\355\212\270 \355\230\270\354\204\235.java" new file mode 100644 index 0000000..7d98f86 --- /dev/null +++ "b/hyejin/Week_8/\352\263\265\354\236\245 \354\273\250\354\204\244\355\204\264\355\212\270 \355\230\270\354\204\235.java" @@ -0,0 +1,61 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BOJ_22254 { + + static int n, x; + static int[] time = new int[100001]; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer stk = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(stk.nextToken()); + x = Integer.parseInt(stk.nextToken()); + + stk = new StringTokenizer(br.readLine()); + for(int i=0; i q = new PriorityQueue<>(); + + for(int i=0; i x) { + return false; + } + q.offer(t + time[i]); + } + + return true; + } +} diff --git "a/hyejin/Week_8/\353\217\204\354\213\234 \352\261\264\354\204\244.java" "b/hyejin/Week_8/\353\217\204\354\213\234 \352\261\264\354\204\244.java" new file mode 100644 index 0000000..f5968f2 --- /dev/null +++ "b/hyejin/Week_8/\353\217\204\354\213\234 \352\261\264\354\204\244.java" @@ -0,0 +1,102 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.StringTokenizer; + +public class BOJ_21924 { + + static class Edge implements Comparable { + int from; + int to; + int dis; + + Edge(int from, int to, int dis) { + this.from = from; + this.to = to; + this.dis = dis; + } + + @Override + public int compareTo(Edge o) { + return this.dis - o.dis; + } + } + + static int n, m; + static ArrayList[] graph = new ArrayList[100001]; + static ArrayList list = new ArrayList<>(); + static int[] parent = new int[100001]; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer stk = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(stk.nextToken()); + m = Integer.parseInt(stk.nextToken()); + + // init + for(int i=1; i<=n; i++) { + parent[i] = i; + } + for(int i=1; i<=n; i++) { + graph[i] = new ArrayList<>(); + } + + long sum = 0; + for (int i = 0; i < m; i++) { + stk = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(stk.nextToken()); + int b = Integer.parseInt(stk.nextToken()); + int c = Integer.parseInt(stk.nextToken()); + + graph[a].add(new Edge(a, b, c)); + graph[b].add(new Edge(b, a, c)); + sum += c; + + list.add(new Edge(a, b, c)); + } + + long mstSum = 0; + + // 거리가 짧은 간선부터 연결 + Collections.sort(list); + + for(int i=0; i queue; + + Gorilla(String name, int n) { + this.name = name; + this.n = n; + queue = new PriorityQueue<>(Collections.reverseOrder()); + } + } + + static HashMap hashMap = new HashMap<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int q = Integer.parseInt(br.readLine()); + StringTokenizer stk; + long result = 0; + + for(int query=0; query g.queue.size()) + n = g.queue.size(); + + for(int i=0; i arr[i] && !visited[i]) { + min = arr[i]; + minIndex = i; + } + } + + // 못찾으면 SKIP + if(minIndex == -1) + return; + + // 찾아냈음.. + visited[minIndex] = true; + // 현재까지 찾은 것 출력 + for(int i=0; i{ + String type; + String name; + long price; + long quality; + + Part(String type, String name, long price, long quality) { + this.type = type; + this.name = name; + this.price = price; + this.quality = quality; + } + + @Override + public int compareTo(Part o) { + return Long.compare(this.price, o.price); +// return this.price - o.price; + } + } + static class PartOrderByQuality implements Comparable{ + String type; + String name; + long price; + long quality; + + PartOrderByQuality(String type, String name, long price, long quality) { + this.type = type; + this.name = name; + this.price = price; + this.quality = quality; + } + + @Override + public int compareTo(PartOrderByQuality o) { + return Long.compare(this.quality, o.quality); +// return this.quality - o.quality; + } + } + + static int n, b; + static HashMap> map; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine()); + + for(int test=0; test(); + + for(int a=0; a()); + parts.offer(part); + map.put(type, parts); + } + + } + solution(); + } + + public static void solution() { + // 성능 순으로 저장하고 있을 큐 + PriorityQueue cq = new PriorityQueue<>(); + + // 제일 싼것들로 조립해본다 + long sum = 0; + for(String type : map.keySet()) { + Part p = map.get(type).poll(); + sum += p.price; + cq.offer(new PartOrderByQuality(p.type, p.name, p.price, p.quality)); + } + + // 제일 퀄리티 낮은 부품을 업그레이드 + long result = 0; + while(true) { + PartOrderByQuality lowest = cq.poll(); + + boolean changeable = false; + Part next = null; + + while(true) { + + // 업그레이드 할 물건이 없으면 ㅂㅂ + if(map.get(lowest.type).isEmpty()) + break; + + next = map.get(lowest.type).poll(); + + // 더 비싼거 꺼내봤는데 퀄리티가 더 낮으면 선택 X + if(next.quality <= lowest.quality) + continue; + + // 예산 안에서 바꿀 수 없음 + if(sum - lowest.price + next.price > b) + break; + + // 위 경우가 아니면 바꿀 수 있는 것임 + changeable = true; + break; + } + if(changeable) { + cq.offer(new PartOrderByQuality(next.type, next.name, next.price, next.quality)); + sum = sum - lowest.price + next.price; + } + else { + result = lowest.quality; + break; + } + + } + System.out.println(result); + } +} diff --git "a/sunguk/src/Week_8/Boj_21924_\353\217\204\354\213\234_\352\261\264\354\204\244.java" "b/sunguk/src/Week_8/Boj_21924_\353\217\204\354\213\234_\352\261\264\354\204\244.java" new file mode 100644 index 0000000..bd01491 --- /dev/null +++ "b/sunguk/src/Week_8/Boj_21924_\353\217\204\354\213\234_\352\261\264\354\204\244.java" @@ -0,0 +1,126 @@ +package Week_8; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.StringTokenizer; + +public class Boj_21924_도시_건설 { + + private int[] parent; + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int buildingCount = Integer.parseInt(st.nextToken()); // N, 3~10^5 3~100000 + int roadCount = Integer.parseInt(st.nextToken()); // M, 2~ + + + long totalPrice = 0; + long minPrice = 0; + List roads = new ArrayList<>(); + + while (roadCount-- > 0) { + st = new StringTokenizer(br.readLine()); + int leftNumber = Integer.parseInt(st.nextToken()); + int rightNumber = Integer.parseInt(st.nextToken()); + int price = Integer.parseInt(st.nextToken()); + totalPrice += price; + Road road = new Road(leftNumber, rightNumber, price); + roads.add(road); + } + + roads.sort(Comparator.naturalOrder()); + + parent = new int[buildingCount + 1]; + for (int i = 0; i < parent.length; i++) { + parent[i] = i; + } + + int selectedRoadCounts = 0; + + for (Road road : roads) { + if (selectedRoadCounts == buildingCount - 1) break; + + int leftBuildingNumber = road.getLeftNumber(); + int rightBuildingNumber = road.getRightNumber(); + + int firstBuildingParentId = findParent(leftBuildingNumber); + int secondBuildingParentId = findParent(rightBuildingNumber); + + if (firstBuildingParentId != secondBuildingParentId) { + syncParentsAsSmallerNumber(leftBuildingNumber, rightBuildingNumber); + minPrice += road.getPrice(); + selectedRoadCounts++; + } + } + + boolean hasFoundAnswer = true; + for (int i = 1; i < buildingCount; i++) { + int firstParent = findParent(i); + int secondParent = findParent(i + 1); + if (firstParent != secondParent) { + hasFoundAnswer = false; + break; + } + } + + if (hasFoundAnswer) { + System.out.println(totalPrice - minPrice); + } else { + System.out.println(-1); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + int findParent(int buildingNumber) { + if (parent[buildingNumber] != buildingNumber) { + parent[buildingNumber] = findParent(parent[buildingNumber]); + } + return parent[buildingNumber]; + } + + void syncParentsAsSmallerNumber(int firstBuildingNumber, int secondBuildingNumber) { + int firstParent = findParent(firstBuildingNumber); + int secondParent = findParent(secondBuildingNumber); + if (firstParent < secondParent) { + parent[secondParent] = firstParent; + } else { + parent[firstParent] = secondParent; + } + } +} + +class Road implements Comparable { + private final int leftNumber; + private final int rightNumber; + private final int price; + + public int getLeftNumber() { + return leftNumber; + } + + public int getRightNumber() { + return rightNumber; + } + + public int getPrice() { + return price; + } + + public Road(int leftBuildingNumber, int rightBuildingNumber, int price) { + this.leftNumber = leftBuildingNumber; + this.rightNumber = rightBuildingNumber; + this.price = price; + } + + @Override + public int compareTo(Road o) { // ascending sort 오름차순 + return price - o.price; + } +} \ No newline at end of file diff --git "a/sunguk/src/Week_8/Boj_22252_\354\240\225\353\263\264_\354\203\201\354\235\270_\355\230\270\354\204\235.java" "b/sunguk/src/Week_8/Boj_22252_\354\240\225\353\263\264_\354\203\201\354\235\270_\355\230\270\354\204\235.java" new file mode 100644 index 0000000..bd77685 --- /dev/null +++ "b/sunguk/src/Week_8/Boj_22252_\354\240\225\353\263\264_\354\203\201\354\235\270_\355\230\270\354\204\235.java" @@ -0,0 +1,52 @@ +package Week_8; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.*; + +/** + * @link https://www.acmicpc.net/problem/22252 + */ +public class Boj_22252_정보_상인_호석 { + + final int EARNING = 1; + final int BUYING = 2; + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int lineCounts = Integer.parseInt(br.readLine()); + Map> gorillaInfoMap = new HashMap<>(); + long total = 0; + while (lineCounts-- > 0) { + String line = br.readLine(); + StringTokenizer st = new StringTokenizer(line, " "); + int command = Integer.parseInt(st.nextToken()); + String gorillaName = st.nextToken(); + if (command == BUYING) { + int buyingCount = Integer.parseInt(st.nextToken()); + PriorityQueue items = gorillaInfoMap.get(gorillaName); + if (items == null) continue; + while (buyingCount-- > 0) { + if (items.isEmpty()) { + break; + } else { + total += items.poll(); + } + } + } else if (command == EARNING) { + PriorityQueue items = gorillaInfoMap.getOrDefault(gorillaName, new PriorityQueue(Comparator.reverseOrder())); + int itemCount = Integer.parseInt(st.nextToken()); + while (itemCount-- > 0) { + items.add(Integer.parseInt(st.nextToken())); + } + gorillaInfoMap.put(gorillaName, items); + } + } + System.out.println(total); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git "a/sunguk/src/Week_8/Boj_22254_\352\263\265\354\240\225_\354\273\250\354\204\244\355\204\264\355\212\270_\355\230\270\354\204\235.java" "b/sunguk/src/Week_8/Boj_22254_\352\263\265\354\240\225_\354\273\250\354\204\244\355\204\264\355\212\270_\355\230\270\354\204\235.java" new file mode 100644 index 0000000..dcccd31 --- /dev/null +++ "b/sunguk/src/Week_8/Boj_22254_\352\263\265\354\240\225_\354\273\250\354\204\244\355\204\264\355\212\270_\355\230\270\354\204\235.java" @@ -0,0 +1,76 @@ +package Week_8; + + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +/** + * @link https://www.acmicpc.net/problem/22254 + */ +public class Boj_22254_공정_컨설턴트_호석 { + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = br.readLine(); + StringTokenizer st = new StringTokenizer(line, " "); + int orderCount = Integer.parseInt(st.nextToken()); + int leftTime = Integer.parseInt(st.nextToken()); + + List orders = new ArrayList(orderCount); + st = new StringTokenizer(br.readLine(), " "); + for (int i = 0; i < orderCount; i++) { + orders.add(new Order(Integer.parseInt(st.nextToken()))); + } + int finalAnswer = orderCount; + + int minFactoryCount = 1; + int maxFactoryCount = orderCount; + int mid = (minFactoryCount + maxFactoryCount) / 2; + + PriorityQueue pq = new PriorityQueue<>(orderCount); + while (minFactoryCount <= maxFactoryCount) { + boolean isPossible = true; + pq.clear(); + for (int i = 0; i < mid; i++) { + pq.offer(0); + } + for (Order order : orders) { + Integer factoryCapacity = pq.poll(); + if (factoryCapacity + order.getTime() > leftTime) { + isPossible = false; + break; + } + pq.offer(factoryCapacity + order.getTime()); + } + if (isPossible) { + finalAnswer = mid; + maxFactoryCount = mid - 1; + } else { + minFactoryCount = mid + 1; + } + mid = (minFactoryCount + maxFactoryCount) / 2; + } + System.out.println(finalAnswer); + } catch (Exception e) { + e.printStackTrace(); + } + } +} + +class Order { + + private final int time; + + public Order(int time) { + this.time = time; + } + + public int getTime() { + return time; + } +} \ No newline at end of file diff --git "a/sunguk/src/Week_8/Boj_3584_\352\260\200\354\236\245_\352\260\200\352\271\214\354\232\264_\352\263\265\355\206\265_\354\241\260\354\203\201.java" "b/sunguk/src/Week_8/Boj_3584_\352\260\200\354\236\245_\352\260\200\352\271\214\354\232\264_\352\263\265\355\206\265_\354\241\260\354\203\201.java" new file mode 100644 index 0000000..94b0c81 --- /dev/null +++ "b/sunguk/src/Week_8/Boj_3584_\352\260\200\354\236\245_\352\260\200\352\271\214\354\232\264_\352\263\265\355\206\265_\354\241\260\354\203\201.java" @@ -0,0 +1,105 @@ +package Week_8; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.*; + +/** + * @link https://www.acmicpc.net/problem/3584 + */ +class Boj_3584_가장_가까운_공통_조상 { + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int caseCount = Integer.parseInt(br.readLine()); + while (caseCount-- > 0) { + Map nodeMap = new HashMap<>(); + int nodeCount = Integer.parseInt(br.readLine()); + while (nodeCount-- > 1) { // N-1 번 노드 정보를 읽음 + String line = br.readLine(); + StringTokenizer st = new StringTokenizer(line, " "); + int parentNum = Integer.parseInt(st.nextToken()); + int childNum = Integer.parseInt(st.nextToken()); + + Node parentNode = nodeMap.getOrDefault(parentNum, new Node(parentNum)); + Node childNode = nodeMap.getOrDefault(childNum, new Node(childNum)); + + parentNode.addChild(childNode); + childNode.setParent(parentNode); + nodeMap.put(parentNum, parentNode); + nodeMap.put(childNum, childNode); + + } + String line = br.readLine(); + StringTokenizer st = new StringTokenizer(line, " "); + int firstNodeNum = Integer.parseInt(st.nextToken()); + int secondNodeNum = Integer.parseInt(st.nextToken()); + + Node firstNode = nodeMap.get(firstNodeNum); + Set parentsSet = getParentsSet(firstNode); + Node currentNode = nodeMap.get(secondNodeNum); + while (!parentsSet.contains(currentNode)) { + currentNode = currentNode.getParent(); + if (currentNode.isRoot()) { + break; + } + } + System.out.println(currentNode.getId()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private Set getParentsSet(Node node) { + Node currentNode = node; + Set parentsSet = new HashSet<>(); + parentsSet.add(currentNode); + while (!currentNode.isRoot()) { + parentsSet.add(currentNode.getParent()); + currentNode = currentNode.getParent(); + } + return parentsSet; + } + + +} + +class Node { + public int getId() { + return id; + } + + public Node getParent() { + return parent; + } + + public List getChildren() { + return children; + } + + private final int id; + private Node parent; + private final List children = new ArrayList<>(); + + public Node(int id) { + this.id = id; + } + + void addChild(Node node) { + if (node != null) { + children.add(node); + } + } + + void setParent(Node node) { + if (node != null) { + parent = node; + } + } + + boolean isRoot() { + return parent == null; + } +} diff --git "a/sunguk/src/Week_9/Boj_10775_\352\263\265\355\225\255.java" "b/sunguk/src/Week_9/Boj_10775_\352\263\265\355\225\255.java" new file mode 100644 index 0000000..03d1c3b --- /dev/null +++ "b/sunguk/src/Week_9/Boj_10775_\352\263\265\355\225\255.java" @@ -0,0 +1,35 @@ +package Week_9; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.TreeSet; + +public class Boj_10775_공항 { + + TreeSet possibleGates = new TreeSet<>(); + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int numberOfGates = Integer.parseInt(br.readLine()); + int numberOfAirplane = Integer.parseInt(br.readLine()); + for (int i = 0; i < numberOfGates; i++) { + possibleGates.add(i + 1); + } + int answer = 0; + while (numberOfAirplane-- > 0) { + int airplaneDockableMaxGateNumber = Integer.parseInt(br.readLine()); + Integer possibleMaxGateNumber = possibleGates.floor(airplaneDockableMaxGateNumber); + if (possibleMaxGateNumber != null) { + possibleGates.remove(possibleMaxGateNumber); + answer++; + } else { + break; + } + } + System.out.println(answer); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/sunguk/src/Week_9/Boj_16719_ZOAC.java b/sunguk/src/Week_9/Boj_16719_ZOAC.java new file mode 100644 index 0000000..8589560 --- /dev/null +++ b/sunguk/src/Week_9/Boj_16719_ZOAC.java @@ -0,0 +1,91 @@ +package Week_9; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.PriorityQueue; + + +/** + * https://www.acmicpc.net/problem/16719 + */ +public class Boj_16719_ZOAC { + + ArrayList characters = new ArrayList<>(); + StringBuilder answer = new StringBuilder(); // 최종 답 출력을 위한 StringBuilder + StringBuilder lastOutputValue = new StringBuilder(); // 최근 값을 저장하는 StringBuilder + boolean[] isChecked; + ArrayList outputArray = new ArrayList(); // 새로운 값이 들어오면 원본순서로 정렬하기 위한 ArrayList + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String inputString = br.readLine(); + for (int i = 0; i < inputString.length(); i++) { + characters.add(new PriorityCharacter(inputString.charAt(i), i)); + } + isChecked = new boolean[inputString.length()]; + findLowestAsciiFromCurrentPosition(0); + if (answer.length() > 0) { + System.out.println(answer.delete(answer.length() - 1, answer.length()).toString()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void findLowestAsciiFromCurrentPosition(int index) { + PriorityQueue pqFromIndex = new PriorityQueue<>((o1, o2) -> { + if(o1.getAsciiCodeValue() == o2.getAsciiCodeValue()){ + return o1.getOriginalPosition() - o2.getOriginalPosition(); + }else { + return o1.getAsciiCodeValue() - o2.getAsciiCodeValue(); + } + }); + for (int i = index; i < characters.size(); i++) { + if (isChecked[i] == false) { + pqFromIndex.offer(characters.get(i)); + } + } + while (!pqFromIndex.isEmpty()) { + PriorityCharacter lowestAscii = pqFromIndex.poll(); + int originalPosition = lowestAscii.getOriginalPosition(); + if (isChecked[originalPosition] == false) { + isChecked[originalPosition] = true; + storeCharacter(originalPosition); + findLowestAsciiFromCurrentPosition(originalPosition + 1); + } + } + } + + private void storeCharacter(int index) { + outputArray.add(characters.get(index)); + outputArray.sort((o1, o2) -> { + return o1.getOriginalPosition() - o2.getOriginalPosition(); + }); + lastOutputValue.delete(0, lastOutputValue.length()); + for (PriorityCharacter priorityCharacter : outputArray) { + lastOutputValue.append((char) priorityCharacter.getAsciiCodeValue()); + } + answer.append(lastOutputValue).append("\n"); + } +} + +class PriorityCharacter { + + private final int asciiCodeValue; + private final int originalPosition; + + public PriorityCharacter(int asciiCodeValue, int originalPosition) { + this.asciiCodeValue = asciiCodeValue; + this.originalPosition = originalPosition; + } + + public int getOriginalPosition() { + return originalPosition; + } + + public int getAsciiCodeValue() { + return asciiCodeValue; + } +} \ No newline at end of file diff --git "a/sunguk/src/Week_9/Boj_3691_\354\273\264\355\223\250\355\204\260_\354\241\260\353\246\275.java" "b/sunguk/src/Week_9/Boj_3691_\354\273\264\355\223\250\355\204\260_\354\241\260\353\246\275.java" new file mode 100644 index 0000000..368e8a6 --- /dev/null +++ "b/sunguk/src/Week_9/Boj_3691_\354\273\264\355\223\250\355\204\260_\354\241\260\353\246\275.java" @@ -0,0 +1,102 @@ +package Week_9; + + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.*; + +/** + * @link https://www.acmicpc.net/problem/3691 + */ +public class Boj_3691_컴퓨터_조립 { + + public void run() { + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int caseCount = Integer.parseInt(br.readLine()); + + while (caseCount-- > 0) { + String line = br.readLine(); + StringTokenizer st = new StringTokenizer(line, " "); + Map partsMap = new HashMap<>(); // key: type, value: parts of type + int numberOfParts = Integer.parseInt(st.nextToken()); + int budget = Integer.parseInt(st.nextToken()); + + while (numberOfParts-- > 0) { + st = new StringTokenizer(br.readLine(), " "); + String type = st.nextToken(); + st.nextToken(); + + int costOfThePart = Integer.parseInt(st.nextToken()); + int qualityOfThePart = Integer.parseInt(st.nextToken()); + PriorityQueue costAscendingPriorityQueue = partsMap.getOrDefault(type, new PriorityQueue(Comparator.comparingInt(Part::getCost))); + costAscendingPriorityQueue.offer(new Part(type, costOfThePart, qualityOfThePart)); + + partsMap.put(type, costAscendingPriorityQueue); + } + + long totalCost = 0L; + PriorityQueue qualityAscendingPriorityQueue = new PriorityQueue<>((o1, o2) -> o1.getQuality() - o2.getQuality()); + for (PriorityQueue pq : partsMap.values()) { // fill with all types of parts + Part cheapPartOfType = pq.poll(); + totalCost += cheapPartOfType.getCost(); + qualityAscendingPriorityQueue.offer(cheapPartOfType); + } + + List collectedQualities = new ArrayList<>(); // it's for figuring it out what the lowest quality of the collected parts is + while (!qualityAscendingPriorityQueue.isEmpty()) { + Part currentLowestQualityPart = qualityAscendingPriorityQueue.poll(); + String type = currentLowestQualityPart.getType(); + if (partsMap.get(type).isEmpty()) { // empty means there is any part of this type + collectedQualities.add(currentLowestQualityPart.getQuality()); // no option to choose + continue; + } + + Part nextCheapPartOfTheType = (Part) partsMap.get(type).poll(); // ready to search better part of this type + if (nextCheapPartOfTheType.getQuality() <= currentLowestQualityPart.getQuality()) { + qualityAscendingPriorityQueue.offer(currentLowestQualityPart); + continue; + } + + int costOfNextPart = nextCheapPartOfTheType.getCost(); + int costOfCurrentPart = currentLowestQualityPart.getCost(); + if (totalCost - costOfCurrentPart + costOfNextPart <= budget) { + totalCost = totalCost - costOfCurrentPart + costOfNextPart; + qualityAscendingPriorityQueue.offer(nextCheapPartOfTheType); // keep next part + } else { + qualityAscendingPriorityQueue.offer(currentLowestQualityPart); // keep current part + } + } + collectedQualities.sort(Comparator.naturalOrder()); + System.out.println(collectedQualities.get(0)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} + +class Part { + private String type; + private int cost; + private int quality; + + Part(String type, int cost, int quality) { + this.type = type; + this.cost = cost; + this.quality = quality; + } + + public String getType() { + return type; + } + + public int getCost() { + return cost; + } + + public int getQuality() { + return quality; + } +} \ No newline at end of file diff --git a/sunguk/src/Week_9/Leet_1855_Maximum_Distance_Between_a_Pair_of_Values.java b/sunguk/src/Week_9/Leet_1855_Maximum_Distance_Between_a_Pair_of_Values.java new file mode 100644 index 0000000..ad99796 --- /dev/null +++ b/sunguk/src/Week_9/Leet_1855_Maximum_Distance_Between_a_Pair_of_Values.java @@ -0,0 +1,33 @@ +package Week_9; + +public class Leet_1855_Maximum_Distance_Between_a_Pair_of_Values { + /** + * find possible distance using binary search + * + * @return 0 if there is not valid pair + */ + public int maxDistance(int[] nums1, int[] nums2) { + int answer = 0; + int min = 1; // searching for distance of 0 is useless + int max = nums2.length; + while (min <= max) { + int mid = (max + min) / 2; + boolean isPossible = false; + for (int i = 0; i < nums1.length; i++) { + if (i + mid < nums2.length) { + if (nums1[i] <= nums2[i + mid]) { + answer = mid; + isPossible = true; + break; + } + } + } + if (isPossible) { + min = mid + 1; + } else { + max = mid - 1; + } + } + return answer; + } +} \ No newline at end of file