Skip to content

Commit 444bce9

Browse files
committed
solve more
1 parent fbbf623 commit 444bce9

5 files changed

+394
-1
lines changed

best-time-to-buy-and-sell-stock-ii.js

+35-1
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,42 @@ var maxProfit = function(prices) {
3131
return s[prices.length - 1];
3232
};
3333

34+
35+
/**
36+
* Memo: Calculate diff and accept it when it is positive.
37+
* Complex: O(n)
38+
* Runtime: 128ms
39+
* Tests: 198 test cases passed
40+
* Rank: S
41+
*/
42+
var maxProfit = function(prices) {
43+
if (prices.length <= 1) {
44+
return 0;
45+
}
46+
47+
var profit = 0;
48+
for (var i = 0; i < prices.length - 1; i++) {
49+
var diff = prices[i + 1] - prices[i];
50+
profit += (diff > 0 ? diff : 0);
51+
}
52+
return profit;
53+
};
54+
55+
var should = require('should');
56+
console.time('Runtime');
57+
maxProfit([]).should.equal(0);
58+
maxProfit([1]).should.equal(0);
59+
maxProfit([1, 2, 3, 4, 5, 6]).should.equal(5);
60+
maxProfit([6, 5, 4, 3, 2, 1]).should.equal(0);
61+
maxProfit([1, 3, 1, 3, 1, 3]).should.equal(6);
62+
maxProfit([1, 3, 1, 4, 1, 5]).should.equal(9);
63+
maxProfit([2, 1, 2, 0, 1]).should.equal(2);
64+
maxProfit([1, 3, 1, 4, 1, 2, 3, 4, 5]).should.equal(9);
65+
66+
console.timeEnd('Runtime');
67+
3468
console.log(maxProfit([3])); //0
35-
console.log(maxProfit([2, 1, 2, 0, 1])); //1
69+
console.log(maxProfit([2, 1, 2, 0, 1])); //2
3670
console.log(maxProfit([1, 2, 3, 4, 5])); //4
3771
console.log(maxProfit([5, 4, 3, 2, 1])); //0
3872
console.log(maxProfit([1, 1, 1, 1, 1])); //0

best-time-to-buy-and-sell-stock.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Source: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
3+
* Tags: [Array,Dynamic Programming]
4+
* Level: Medium
5+
* Title: Best Time to Buy and Sell Stock
6+
* Auther: @imcoddy
7+
* Content: Say you have an array for which the ith element is the price of a given stock on day i.
8+
*
9+
* If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
10+
*/
11+
12+
/**
13+
* @param {number[]} prices
14+
* @return {number}
15+
*/
16+
17+
/**
18+
* Memo: Create an array of prices differences, then turn this problem into maximum subarray. https://leetcode.com/problems/maximum-subarray/
19+
* Complex: O(n)
20+
* Runtime: 148ms
21+
* Tests: 198 test cases passed
22+
* Rank: B
23+
*/
24+
var maxProfit = function(prices) {
25+
if (prices.length <= 1) {
26+
return 0;
27+
}
28+
29+
var maxSubArray = function(nums) {
30+
var s = [nums[0]];
31+
var max = s[0];
32+
for (var i = 1; i < nums.length; i++) {
33+
s[i] = Math.max(s[i - 1] + nums[i], nums[i]);
34+
if (s[i] > max) {
35+
max = s[i];
36+
}
37+
}
38+
return max;
39+
};
40+
41+
var diff = [];
42+
for (var i = 0; i < prices.length - 1; i++) {
43+
diff[i] = prices[i + 1] - prices[i];
44+
}
45+
var profit = maxSubArray(diff);
46+
return profit > 0 ? profit : 0;
47+
48+
// var profit = 0;
49+
// for (var i = 0; i < prices.length - 1; i++) {
50+
// var diff = prices[i + 1] - prices[i];
51+
// profit += (diff > 0 ? diff : 0);
52+
// }
53+
// return profit;
54+
};
55+
56+
var should = require('should');
57+
console.time('Runtime');
58+
maxProfit([]).should.equal(0);
59+
maxProfit([1]).should.equal(0);
60+
maxProfit([1, 2, 3, 4, 5, 6]).should.equal(5);
61+
maxProfit([6, 5, 4, 3, 2, 1]).should.equal(0);
62+
maxProfit([1, 3, 1, 3, 1, 3]).should.equal(2);
63+
maxProfit([1, 3, 1, 4, 1, 5]).should.equal(4);
64+
maxProfit([2, 1, 2, 0, 1]).should.equal(1);
65+
maxProfit([1, 3, 1, 4, 1, 2, 3, 4, 5]).should.equal(4);
66+
67+
console.timeEnd('Runtime');

contains-duplicate.js

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* Source: https://leetcode.com/problems/contains-duplicate/
3+
* Tags: [Array,Hash Table]
4+
* Level: Easy
5+
* Title: Contains Duplicate
6+
* Auther: @imcoddy
7+
* Content: Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {boolean}
13+
*/
14+
15+
/**
16+
* Memo:
17+
* Complex: O(n)
18+
* Runtime: 148ms
19+
* Tests: 16 test cases passed
20+
* Rank: NA
21+
*/
22+
var containsDuplicate = function(nums) {
23+
var map = {};
24+
for (var i = 0; i < nums.length; i++) {
25+
if (map[nums[i]]) {
26+
return true;
27+
}
28+
map[nums[i]] = true;
29+
}
30+
return false;
31+
};
32+
33+
34+
/**
35+
* Memo: easiest but worst solution probably.
36+
* Complex: O(n^2)
37+
* Runtime: 1384ms
38+
* Tests: 16 test cases passed
39+
* Rank: D
40+
*/
41+
var containsDuplicate = function(nums) {
42+
for (var i = 0; i < nums.length - 1; i++) {
43+
for (var j = i + 1; j < nums.length; j++) {
44+
if (nums[i] === nums[j]) {
45+
return true;
46+
}
47+
}
48+
}
49+
return false;
50+
};
51+
52+
/**
53+
* Memo: Sort array first and find element which is duplicate to its next.
54+
* Complex: O(nlgn)
55+
* Runtime: 160ms
56+
* Tests: 16 test cases passed
57+
* Rank: NA
58+
*/
59+
var containsDuplicate = function(nums) {
60+
if (nums.length <= 1) {
61+
return false;
62+
}
63+
var a = nums.sort();
64+
for (var i = 0; i < a.length - 1; i++) {
65+
if (a[i] === a[i + 1]) {
66+
return true;
67+
}
68+
}
69+
return false;
70+
};
71+
72+
var should = require('should');
73+
console.time('Runtime');
74+
containsDuplicate([3, 5, 1, 9, 7]).should.equal(false);
75+
containsDuplicate([1, 3, 5, 7, 9]).should.equal(false);
76+
containsDuplicate([1, 3, 5, 7, 1]).should.equal(true);
77+
78+
console.timeEnd('Runtime');

count-primes.js

+185
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
/**
2+
* Source: https://leetcode.com/problems/count-primes/
3+
* Tags: [Hash Table,Math]
4+
* Level: Easy
5+
* Title: Count Primes
6+
* Auther: @imcoddy
7+
* Content: Description:
8+
* Count the number of prime numbers less than a non-negative number, n.
9+
*
10+
* Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
11+
*
12+
* Hint:
13+
* Show Hint
14+
*
15+
*
16+
*
17+
* Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
18+
* Show More Hint
19+
*
20+
*
21+
* As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?
22+
* Show More Hint
23+
*
24+
*
25+
* Let's write down all of 12's factors:
26+
*
27+
* 2 × 6 = 12
28+
* 3 × 4 = 12
29+
* 4 × 3 = 12
30+
* 6 × 2 = 12
31+
*
32+
*
33+
* As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
34+
*
35+
* Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
36+
*
37+
*
38+
* public int countPrimes(int n) {
39+
* int count = 0;
40+
* for (int i = 1; i < n; i++) {
41+
* if (isPrime(i)) count++;
42+
* }
43+
* return count;
44+
* }
45+
*
46+
* private boolean isPrime(int num) {
47+
* if (num
48+
* Show More Hint
49+
*
50+
*
51+
* The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
52+
*
53+
*
54+
*
55+
* Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
56+
*
57+
*
58+
* We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well?
59+
* Show More Hint
60+
*
61+
*
62+
* 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off?
63+
* Show More Hint
64+
*
65+
*
66+
* In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition?
67+
* Show More Hint
68+
*
69+
*
70+
* It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3?
71+
* Show More Hint
72+
*
73+
*
74+
* Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
75+
*
76+
* The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
77+
*
78+
*
79+
* public int countPrimes(int n) {
80+
* boolean[] isPrime = new boolean[n];
81+
* for (int i = 2; i < n; i++) {
82+
* isPrime[i] = true;
83+
* }
84+
* // Loop's ending condition is i * i < n instead of i < sqrt(n)
85+
* // to avoid repeatedly calling an expensive function sqrt().
86+
* for (int i = 2; i * i < n; i++) {
87+
* if (!isPrime[i]) continue;
88+
* for (int j = i * i; j < n; j += i) {
89+
* isPrime[j] = false;
90+
* }
91+
* }
92+
* int count = 0;
93+
* for (int i = 2; i < n; i++) {
94+
* if (isPrime[i]) count++;
95+
* }
96+
* return count;
97+
* }
98+
*/
99+
100+
/**
101+
* @param {number} n
102+
* @return {number}
103+
*/
104+
105+
/**
106+
* Memo: Add a method to check if current number is prime or not, then count from 2 to n;
107+
* Complex: O(nlogn)
108+
* Runtime: ms
109+
* Tests: 20 test cases passed
110+
* Rank: D
111+
*/
112+
var countPrimes = function(n) {
113+
var isPrime = function(n) {
114+
if (n <= 1) {
115+
return false;
116+
}
117+
var root = Math.sqrt(n);
118+
for (var i = 2; i <= root; i++) {
119+
if (n % i === 0) {
120+
return false;
121+
}
122+
}
123+
return true;
124+
};
125+
126+
var count = 0;
127+
for (var i = 2; i < n; i++) {
128+
if (isPrime(i)) {
129+
count++;
130+
}
131+
}
132+
return count;
133+
};
134+
135+
136+
/**
137+
* Memo: User a map to track if the number is prime or not. Once a prime number is found, mark other multiples as not prime number.
138+
* Complex: O(nlogn)
139+
* Runtime: 304ms
140+
* Tests: 20 test cases passed
141+
* Rank: A
142+
*/
143+
var countPrimes = function(n) {
144+
if (n <= 2) {
145+
return 0;
146+
}
147+
148+
var isPrime = [0, 0];
149+
for (var i = 2; i < n; i++) {
150+
isPrime[i] = i;
151+
}
152+
153+
for (var i = 2; i * i <= n; i++) {
154+
if (isPrime[i]) {
155+
var t = i * i;
156+
while (t < n) {
157+
isPrime[t] = 0;
158+
t += i;
159+
}
160+
}
161+
}
162+
163+
var count = 0;
164+
for (var i = 2; i < isPrime.length; i++) {
165+
if (isPrime[i]) {
166+
count++;
167+
}
168+
}
169+
//console.log(n, count, isPrime);
170+
return count;
171+
};
172+
173+
var should = require('should');
174+
console.time('Runtime');
175+
countPrimes(-1).should.equal(0);
176+
countPrimes(0).should.equal(0);
177+
countPrimes(1).should.equal(0);
178+
countPrimes(2).should.equal(0);
179+
countPrimes(3).should.equal(1);
180+
countPrimes(4).should.equal(2);
181+
countPrimes(5).should.equal(2);
182+
countPrimes(6).should.equal(3);
183+
countPrimes(25).should.equal(9);
184+
185+
console.timeEnd('Runtime');

0 commit comments

Comments
 (0)