[Easy] 1299. Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
// time:O(n^2) space:O(n) publicint[] replaceElements(int[] arr) { if (arr == null || arr.length == 0) returnnewint[]{}; int[] res = newint[arr.length];
for (int i = 0; i < arr.length; i++) { int max = -1; for (int j = i + 1; j < arr.length; j++) { max = Math.max(max, arr[j]); } res[i] = max; } return res; }
// time:O(n) space:O(1) publicint[] replaceElements2(int[] arr) { // look backward if (arr == null || arr.length == 0) returnnewint[]{}; int max = -1; for (int i = arr.length - 1; i >= 0; i--) { int temp = arr[i]; arr[i] = max; max = Math.max(max, temp); } return arr; }
1300. Sum of Mutated Array Closest to Target
Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.
In case of a tie, return the minimum such integer.
Notice that the answer is not neccesarilly a number from arr.
Example
1 2 3 4 5 6 7 8 9
Input: arr = [4,9,3], target = 10 Output: 3 Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.
We can use either DFS or BFS, for the DFS, first we need to calculate the maximum depth and use that value to helpe return the deepest node val, otherwise, it returns 0. And then we have to sum up left side and right side. For the BFS, we just need to keep tracking sum of each level and at the end, return the last level’s vlaue.
// DFS // time:O(n) space:O(n) publicintdeepestLeavesSum(TreeNode root){ if (root == null) return0; int depth = maxDis(root); return helperWithReturn(root, depth); }
publicinthelperWithReturn(TreeNode root, int level){ if (root == null) return0; if (level == 1) return root.val;// at the deepest node. int left = helperWithReturn(root.left,level - 1); int right = helperWithReturn(root.right, level - 1); return left + right; }
publicintmaxDis(TreeNode root){ if (root == null) return0; int left = maxDis(root.left); int right = maxDis(root.right); return Math.max(left, right) + 1; }
// BFS // time:O(n) space:O(n) publicintdeepestLeavesSum2(TreeNode root){ if (root == null) return0; Queue<TreeNode> queue = new LinkedList<>(); int sum = 0; queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); sum = 0; // calculate each level. for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); sum += node.val; if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } } return sum; }