Documenting LeetCode solving.
Q93
Medium. 1D DP.
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int a = 1; a <= amount; a++) {
for (int c : coins) {
if (a - c >= 0) {
dp[a] = Math.min(dp[a], 1 + dp[a - c]);
}
}
}
return dp[amount] != amount + 1 ? dp[amount] : -1;
}
}
Q94
Medium. 1D DP.
class Solution {
public int maxProduct(int[] nums) {
int currMax = 1, currMin = 1;
int res = nums[0];
for (int n : nums) {
int tmp = n * currMax;
currMax = Math.max(Math.max(n * currMax, n * currMin), n);
currMin = Math.min(Math.min(tmp, n * currMin), n);
res = Math.max(res, currMax);
}
return res;
}
}
R14
121. Best Time to Buy and Sell Stock
Easy.
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
int lowest = prices[0];
for (int p : prices) {
if (p < lowest) {
lowest = p;
}
res = Math.max(res, p - lowest);
}
return res;
}
}
R15
3. Longest Substring Without Repeating Characters
Medium.
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> charSet = new HashSet<>();
int res = 0;
int l = 0;
for (int r = 0; r < s.length(); r++) {
while (charSet.contains(s.charAt(r))) {
charSet.remove(s.charAt(l));
l++;
}
charSet.add(s.charAt(r));
res = Math.max(res, r - l + 1);
}
return res;
}
}
R16
424. Longest Repeating Character Replacement
Medium.
class Solution {
public int characterReplacement(String s, int k) {
Map<Character, Integer> count = new HashMap<>();
int res = 0;
int l = 0;
// Track max frequent char so far.
int maxf = 0;
for (int r = 0; r < s.length(); r++) {
count.put(s.charAt(r), count.getOrDefault(s.charAt(r), 0) + 1);
maxf = Math.max(maxf, count.get(s.charAt(r)));
while ((r - l + 1) - maxf > k) {
count.put(s.charAt(l), count.get(s.charAt(l)) - 1);
l++;
}
res = Math.max(res, r - l + 1);
}
return res;
}
}
R17
Medium.
class Solution {
public boolean checkInclusion(String s1, String s2) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
for (char c : s1.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}
int l = 0, r = 0;
int match = 0;
while (r < s2.length()) {
char rc = s2.charAt(r);
r++;
if (need.containsKey(rc)) {
window.put(rc, window.getOrDefault(rc, 0) + 1);
if (need.get(rc).equals(window.get(rc))) {
match++;
}
}
while (r - l + 1 > s1.length()) {
if (match == need.size()) {
return true;
}
char lc = s2.charAt(l);
l++;
if (need.containsKey(lc)) {
if (need.get(lc).equals(window.get(lc))) {
match--;
}
window.put(lc, window.get(lc) - 1);
}
}
}
return false;
}
}