Skip to content

Instantly share code, notes, and snippets.

View kkchu791's full-sized avatar

Kirk Chu kkchu791

  • Los Angeles, CA
View GitHub Profile
# Raindrops
Convert a number to a string, the contents of which depend on the number's factors.
- If the number has 3 as a factor, output 'Pling'.
- If the number has 5 as a factor, output 'Plang'.
- If the number has 7 as a factor, output 'Plong'.
- If the number does not have 3, 5, or 7 as a factor,
just pass the number's digits straight through.
ass TreeNode
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
end
tree = TreeNode.new(5)
tree.left = TreeNode.new(3)
var minCostClimbingStairs = function(cost) {
for (let i = 2; i < cost.length; i++) {
cost[i] += Math.min(cost[i-1], cost[i-2]);
}
return Math.min(cost[cost.length-1], cost[cost.length-2]);
};
@kkchu791
kkchu791 / house_robber3.js
Created March 19, 2019 13:45
recursive ways
var rob = function(nums) {
}
@kkchu791
kkchu791 / house_robber2.js
Last active March 19, 2019 13:37
another solution in linear time
var rob = function(nums) {
var prevEvenMax = 0;
var prevOddMax = 0;
for (var i = 0; i < nums.length; i++) {
if (i % 2 === 0) {
prevEvenMax = Math.max(prevEvenMax + nums[i], prevOddMax);
}
else {
prevOddMax = Math.max(prevEvenMax, prevOddMax + nums[i]);
@kkchu791
kkchu791 / house_robber.js
Created March 19, 2019 13:21
linear time solution
var rob = function(profits) {
let prevMaxProfit = 0;
let currMaxProfit = 0;
for (let i = 0; i < profits.length; i++) {
const prevPlusProfit = prevMaxProfit + profits[i];
prevMaxProfit = currMaxProfit;
currMaxProfit = Math.max(currMaxProfit, prevPlusProfit);
}
@kkchu791
kkchu791 / maximum_subarray.js
Last active March 18, 2019 18:53
linear solving of maximum subarray problem (dynamic programming)
// Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
// Example:
// Input: [-2,1,-3,4,-1,2,1,-5,4],
// Output: 6
// Explanation: [4,-1,2,1] has the largest sum = 6.
// Follow up:
// If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
@kkchu791
kkchu791 / squares_of_sorted_array.js
Created February 24, 2019 20:43
Using insertion sort
// Given an array of integers A sorted in non-decreasing order,
// return an array of the squares of each number, also in sorted non-decreasing order.
// array = [-4,-1,0,3,10]
const sortedSquares = (array) => {
// square the elements in the array
const squaredArray = array.map(el => el * el);
// use insertion sort to sort the array from min to max
# nums = [2, 3, 11, 22], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
#return [0, 1]
def two_sum(nums, target)
nums.each do |i|
nums.each do |x|
if i + x == target && nums.index(i) != nums.index(x)
return [nums.index(i), nums.index(x)]
end