Greedy algorithm java

Posted by simrx11 on Thu, 04 Nov 2021 11:13:53 +0100

Minimum dictionary order

Given a string type array strs, find a splicing method so that the string formed after splicing all strings has the smallest dictionary order

public class LowestLexicography {

    public static class MyComparator implements Comparator<String>{
        @Override
        public int compare(String o1, String o2) {
            return (o1+o2).compareTo(o2+o1);
        }
    }

    public static String lowestString(String[] strs){
        if (null == strs || strs.length == 0){
            return "";
        }
        Arrays.sort(strs,new MyComparator());
        String str = "";
        for (int i = 0; i < strs.length; i++) {
            str += strs[i];
        }
        return str;
    }

    public static void main(String[] args) {
        String[] strs1 = { "jibw", "ji", "jp", "bw", "jibw" };
        System.out.println(lowestString(strs1));

        String[] strs2 = { "ba", "b" };
        System.out.println(lowestString(strs2));
    }
}

Gold bar cutting problem

Cutting a gold bar into two halves requires copper plates with the same length value. For example, a gold bar with a length of 20 needs 20 copper plates no matter how long it is cut into two halves
A group of people want to share a gold bar. How to share the most economical copper plate
For example, given the array {10,20,30}, it represents a total of 3 people, and the length of the whole gold bar is 10 + 20 + 30 = 60,
Gold bars are divided into three parts: 10, 20 and 30
If the gold bar with a length of 60 is divided into 10 and 50, it will cost 60 copper plates, and then 50 into 20 and 30, it will cost 50 copper plates, a total of 110 copper plates
If the gold bar with a length of 60 is divided into 2 bars and 30 bars, 60 copper plates will be spent, and then one of the gold bars with a length of 30 will be divided into 10 and 20, 30 copper plates will be spent, a total of 90 copper plates will be spent
Enter an array and return the minimum cost of segmentation (Huffman algorithm)

[idea] prepare a small root heap, add the two smallest elements, put them into the small root heap, add the two smallest values, put them back into the small root heap, and cycle until there is only one element in the small root heap, which is the final result

public class LessMoneySplitGold {

    public static int lessMoney(int[] arr){
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int i : arr) {
            queue.add(i);
        }
        int sum = 0;
        int cur = 0;
        while (queue.size() > 1){
            int a = queue.poll();
            int b = queue.poll();
            cur = a + b;
            sum = sum + cur;
            queue.add(cur);
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] arr = {10,20,30};
        int money = lessMoney(arr);
        System.out.println(money);
    }
}

Number of lectures in the conference room

Some projects need to occupy a conference room for publicity. The conference room cannot accommodate the publicity of two projects at the same time. The publicity schedule is arranged for the start time and end time of each project, and the conference room is required to conduct the most publicity. Return to the most lectures

[idea] select the item less than the specified start time, select the item with the earliest end time, cycle, find out all items, and return the number of items

public class Code04_BestArrange {

    public static class Program{
    	//start time
        public int start;
        //End time
        public int end;

        public Program(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

    public static class ProgramComparator implements Comparator<Program>{

        @Override
        public int compare(Program o1, Program o2) {
            return o1.end - o2.end;
        }
    }

    public static int bestArrange(Program[] programs, int start){
        Arrays.sort(programs,new ProgramComparator());
        int res = 0;
        for (int i = 0; i < programs.length; i++) {
            if (start <= programs[i].start){
                System.out.println(programs[i].start+","+programs[i].end);
                res++;
                start = programs[i].end;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Program program1 = new Program(6, 8);
        Program program2 = new Program(7, 9);
        Program program3 = new Program(9, 12);
        Program program4 = new Program(11, 13);
        Program program5 = new Program(14, 16);
        Program program6 = new Program(15, 18);
        Program program7 = new Program(17, 18);
        Program[] programs = {program1,program2,program3,program4,program5,program6,program7};

        int arrange = bestArrange(programs, 6);
        System.out.println(arrange);
    }
}

Get the maximum amount of money

Enter the positive array costs costs[i] to represent the cost of item I
Enter the positive array profits profits [i] to represent the profit of item I
A positive number k can serial up to K items
Positive m initial fund
Every time you finish a project, you will get benefits immediately, which can support you to do the next project
Output: the maximum amount of money finally obtained

[idea] prepare two root piles, one large root pile and one small root pile. The small root pile is used to store the small root pile according to cost, and the large root pile is the data taken from the small root pile, which is sorted according to the large root pile of profit
First select the items that meet the principal from the small root pile and put them into the big root pile. Take out the items with the largest profit. After obtaining the largest profit, then take out the principal that meets the obtained profit from the small root pile and put them into the big root pile. Take out the items with the largest profit again and repeat until there is no project to do, and return the maximum amount of money

public class IPO {
    public static class Node{
        //profit
        public int p;
        //cost
        public int c;

        public Node(int p, int c) {
            this.p = p;
            this.c = c;
        }
    }

    public static class MaxHeapComparator implements Comparator<Node> {

        @Override
        public int compare(Node o1, Node o2) {
            return o2.p - o1.p;
        }
    }

    public static class MinHeapComparator implements Comparator<Node> {

        @Override
        public int compare(Node o1, Node o2) {
            return o1.c - o2.c;
        }
    }

    /**
     *
     * @param k Up to k items that can be serialized
     * @param m Initial capital
     * @param profits Project profit set
     * @param costs Project cost collection
     * @return
     */
    public static int findMaximizedCapital(int k, int m, int[] profits, int[] costs){
        Node[] nodes = new Node[profits.length];
        for (int i = 0; i < profits.length; i++) {
            nodes[i] = new Node(profits[i], costs[i]);
        }
        PriorityQueue<Node> minHeapQueue = new PriorityQueue<>(new MinHeapComparator());
        PriorityQueue<Node> maxHeapQueue = new PriorityQueue<>(new MaxHeapComparator());

        for (Node node : nodes) {
           minHeapQueue.add(node);
        }
        for (int i = 0; i < k; i++) {
            while (!minHeapQueue.isEmpty() &&  minHeapQueue.peek().c <= m){
                maxHeapQueue.add(minHeapQueue.poll());
            }
            if (maxHeapQueue.isEmpty()){
                return m;
            }
            m += maxHeapQueue.poll().p;
        }
        return m;
    }

    public static void main(String[] args) {
        int k = 3;
        int m = 4;
        int[] profits = {5,3,6,7};
        int[] costs = {4,2,6,8};

        int capital = findMaximizedCapital(k, m, profits, costs);
        System.out.println(capital);
    }
}

Common methods:

  1. Establish a comparator to sort according to a certain standard
  2. A comparator is established according to a standard to form a heap

To be clear, the above codes are arranged according to Mr. Zuo Chengyun's algorithm course. If you are interested, go to station b to see the corresponding free courses

Topics: Java Programming Algorithm greedy algorithm