leetcode--greedy

  1. Best Time to Buy and Sell Stock II
class Solution {
    public int maxProfit(int[] prices) {
        int[] deltas = new int[prices.length];
        
        for (int i = 0; i < prices.length - 1; i++) {
            deltas[i] = prices[i+1] - prices[i];
        }
        
        int ret = 0;
        
        for (int v : deltas) {
            if (v > 0)
                ret += v;
        }
        
        return ret;
    }
}
  1. Assign Cookies
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int g_i = g.length-1;
        int s_i = s.length-1;
        int count = 0;
        while(g_i >=0 && s_i >= 0) {
            if(s[s_i] >= g[g_i]) {
                count++;
                s_i--;
            }
            g_i--;
        }
        return count;
    }
}
  1. Queue Reconstruction by Height
class Solution {
    public int[][] reconstructQueue(int[][] people){
if(people == null || people.length == 0){
        return new int[][]{};
}
Arrays.sort(people, new Comparator(){
    public int compare(int[] o1, int[] o2){
        return o1[0] != o2[0] ? o2[0] - o1[0] : o1[1] - o2[1];
}
});
List res = new ArrayList<>();
for(int[] cur: people){
    res.add(cur[1], cur);
}
return res.toArray(new int[people.length][2]);
}

}
  1. Is Subsequence
sample 4 ms submission
class Solution {
    public boolean isSubsequence(String s, String t) {
        char[] cc = s.toCharArray();
        int last = 0;
        for (int i = 0; i < cc.length; i++) {
            int index = t.indexOf(cc[i], last);
            if (index < 0) {
                return false;
            }
            last = index + 1;
        }
        return true;
    }
}
  1. Task Scheduler
class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] taskCounts = new int[26];
        for(char task: tasks) {
            taskCounts[task-'A']++;
        }
        
        int max = 0;
        int elementsWithMax = 0;
        for(int count: taskCounts) {
            if (count == max) {
                elementsWithMax++;
            } else if (count > max) {
                max = count;
                elementsWithMax = 1;
            }
        }
        
        return Math.max(tasks.length, (max-1)*(n+1) + elementsWithMax);
    }
}

你可能感兴趣的:(leetcode--greedy)