Algorithms

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nums = [1] Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Output: 23

Dynamic Programming: Use tracker array to solve subproblems. Set initial value of tracker array to be nums[0]. Iterate through the input array. At each cycle, find the bigger of (currentNumber, currentNumber+previousNumber in trackerArray). This works because at any point in time, we know the best sum we can do in the previous cell. int[] trackSum = new int[nums.length]; trackSum[0] = nums[0]; for (int i = 1; i < nums.length; i++) { trackSum[i] = Math.max(nums[i], nums[i]+trackSum[i-1]); maxSum = Math.max(maxSum, trackSum[i]); } Time: O(n) Space: O(n)

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]]

Backtracking: Need to utilize a helper method to implement backtracking method. Initialize a global variable to capture results. Backtracking helper method will implement recursion. - terminating condition is if temp list is the same length as input list. - visited boolean [] will help to not add duplicate numbers Loop through the list, if visited is true, skip. Else add to list, update visited and pass back into recusrive method. Backtrack by removing from list and updating visited to false. for (int i = 0; i < nums.length; i++) { if (visited[i]) continue; visited[i] = true; temp.add(nums[i]); btHelper(nums, temp, visited); visited[i] = false; temp.remove(temp.size()-1); }

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: nums = [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. Example 2: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 3: Input: nums = [1,2,3] Output: 3

Bottom Up Dynamic Programming: Solve for house robber 1 but run it twice. DP only works if there is a "BASE CASE". Since the houses are circular, there is no starting point. Run DP TWICE, once without the first house and one more time without the last house. The idea is that we find two local maximums, using all the numbers. We then return the bigger of the maximum.. This works because if you run the first number, you can rob the last. Vice Versa. Time: O(n) Space: O(1)

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. A subarray is a contiguous subsequence of the array. Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Brute Force: Find every possible combination of subarray numbers in list. -------------------------------------------------- Track Min and Max: Use three variables to track the local min, max and global max. min, max, res. Set all numbers to 0 initially. Loop through the list of integers, at each cycle calculate the - max as bigger of (currentNumber, currentNumber*max) - min as smaller of (currentNumber, currentNumber*min) - res as bigger number of (res, max) If the current number is negative, swap min and max. We need to track min incase there is another negative number to turn it back positive. Local maxes dont matter because we are capturing them in res. 0's are taken care of because we check currentNumber. If currentNumber is non-zero and previous is, we can ignore the previous 0. for (int i = 1; i < nums.length; i++) { if (nums[i] < 0) { int temp = max; max = min; min = temp; } max = Math.max(nums[i], max*nums[i]); min = Math.min(nums[i], min*nums[i]); res = Math.max(res, max); }

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step

Brute Force: Use recursion and pass in possible combinations of moves at current step. Terminate: when step is <= 0, return 0 when step is at 1, return 1. if step > 1, try both -2 and -1 steps. Make sure to use memoization to save on time. Time: O(2^n) Space: O(n) ---------------------- Bottom-Up Dynamic Programming: Initialize array of length n+1, and values of table[1]=1 and table[2]=2. Loop through each index of table. At each cycle, add values of i-1, and i-2. table[i] = table[i-1] + table[i-2] Time: O(n) Space: O(n)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

Brute Force: Use recursion to find all possible combination given skip condition of next house. ------------- Bottom Up Dynamic Programming: Using two variables, track the best sum we can do at oneHouse Before and Two Houses Before. Use two variables, oneHouseBefore = 0, twoHousesBefore = 0 Loop through all numbers. At each cycle, track a temp. temp = Math.max(currentNumber + twoHousesBefore, oneHouseBefore) The logic here is that if we take the current value, we cant add the value right before, but we can add everything before that. If we dont take the current value, we can take the best up to the value right before. Time: O(n) Space: O(1)

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. Example 1: Input: cost = [10,15,20] Output: 15 Explanation: You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. Example 2: Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6 Explanation: You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6.

Brute Force: Use recursion to find all possible temps to end. Sum up all and return smallest. Time: O(2^n) two possible choices at each step Space: O(n)? ----- Bottom Up DP: This is similar to house robber. Use two pointers to track oneHouseBefore and twoHouseBefore. At any given index, you can either get there by one houeBefore or two houses before. The capture the smaller of the two numbers for that. int temp = Math.min(cost[i]+oneBefore, cost[i]+twoBefore); twoBefore = oneBefore; oneBefore = temp; Return the smaller of the two at the end. Time: O(n) Space: O(1)

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0

Brute Force: Use recursion to implement combination sum. At each cycle, subtract current coin from target. Try this at every coin. Will have multiple combination of coins at the end. Time: O(C^n) C is target. n is coins Space: O(C) ----------- Bottom Up Dynamic Programming: Using an array, track the min coins needed for sub-problems. Initialize an array of size target+1. The value of each index is target+1. We do this because it's impossible to have more coin amount than your target number since the smallest coin is 1. Loop through every index, at each cycle calculate index - each coin value If its negative, the coin is too big, skip. If its positive or 0, check the value of this result against the tracker array. Set the current value of the tracker array to be smaller of (1+tracker(diff), tracker(i)) Return the last value of the tracker array if its not == target+1 Time: O(C*n) Space: O(n)

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. Example 2: Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Brute Force: Using custom comparator, sort the input array and return k values starting at beginning. Arrays.sort(input, (a,b) ->{logic here}) Time: O(nlogn) Space: O(n) --------- Min Heap: Use a minHeap and limit size to k. Keeping the size to k means a time complexity of Time: O(nlogk) Space: O(k)

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]

Brute Force: Using three nested for loops, find every possible combination of 3 numbers. Time: O(n^3) Space: O(1) -------------------------------------------------- Sorted with Pointers: First sort the input array. Then loop through every value of the array. Find the complement at each number. comp = 0 - nums[i] At each value, use two pointers (low and high) and loop through the remaining numbers starting at the ends and move inward to find the sum adding up to complement. If sum > comp, high-- If sum < comp, low++ Edge Cases: - if answer found, make sure next high and low are not duplicate. keep incrementing both until tru - if nums[i] is > 0, cant sum three numbers to 0, break early - if next nums[i] is same, skip Time: O(n^2) Space: O(n)

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true

Brute Force: Using two for loops, find every pair of combination of numbers in the list. If another number exists that matches current, return true. Time: O(n^2) Space: O(1) -------------------------------------------------- HashMap Counter: Initialize a HashSet of Integer. Loop through the list and add number to HashSet. Check if the current number exists with Set.contains(). If true, return true. Else keep looping and adding. Time: O(n) Space: O(n)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Input: nums = [2,7,11,15], target = 9 Output: [0,1]

Brute Force: Using two for loops, try every combination of two numbers. Time: O(n^2) Space: O(n) -------------------------------------------------- HashMap: Using a hashmap to track numbers and their indices, loop through the list and compute the complement of each number. comp = target - nums[i] If comp is in HashMap, it means there exists another number that is the complement of the existing number. Return both. If not, add current number and index. Time: O(n) Space: O(n)

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container. Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Brute Force: Using two nested for loops, find every possible combination of two numbers. Calculate their area. Time: O(n^2) Space: O(1) -------------------------------------------------- Two Pointers: Using two pointers set at the ends of the list, calculate subsequent area by moving the pointers inward. Since the width of the area is at its max at the initial condition, only calculate new area when the height of one of the pointers > min height. Dont need to calculate area if both width and height are decreasing. - find min height - move smaller height pointer inward until height > minHeight - calculate area Time: O(n) Space: O(1)

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. Input: m = 3, n = 7 Output: 28 Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down

Dynamic Programming: Initialize a tracker matrix with same size as input matrix. Use this matrix to save previous calculations of moves of sub-problem. Loop through every index of input matrix with row and col. There are three possible conditions at any point in time - row > 0 && col > 0 : add the number from tracker matrix of row-1 and col-1 - row > 0 : col is 0 so just add the row-1 number - col > 0 : row is 0 so just add the col-1 number Return last index of tracker matrix. Time: O(mxn) Space: O(mxn) -------------------------------------------------- Improvements: Use a n size array to scan and capture results instead of using an entire matrix. int[] sumGrid = new int[n]; sumGrid[0] = 1; for (int row = 0; row < m; row++) { for (int col = 0; col < n; col++) { if (row>0 && col>0) sumGrid[col] += sumGrid[col-1]; else sumGrid[col] = 1; } } return sumGrid[n-1];


Set pelajaran terkait

MICROECONOMICS CH16 and 17 Monopolistic Competition and Oligopolies

View Set

Engineering and Tech A Unit #6 - Use of Technology for Engineering Design

View Set

chapter 12 incident investigations

View Set

Environmental Chem Chp 3 (68 CONCEPTS)

View Set