Basic algorithm record (2) - some common algorithm problems

The Best Time to Buy and Sell Stocks II

Suppose there is an array whose ith element is the price of a given stock on the ith day. Design an algorithm to find the maximum profit. You can complete as many trades as you want (buy and sell stocks multiple times). However, you cannot participate in multiple trades at the same time (you must sell the stock before buying it again).

Idea: The greedy method can be used, as long as the price tomorrow is higher than today, then buy today and sell tomorrow, otherwise do not buy today. Then continue to look at the day after tomorrow and tomorrow, and so on

class Solution {
public static void main(String [] args){
    Solution s = new Solution();
    Scanner sc = new Scanner(System.in);
    int count = sc.nextInt();
    int [] nums = new int[count];
    for(int k=0;k<nums.length;k++){
        nums[k] = sc.nextInt();
    }
    sc.close();
    int rs = s.maxProfit(nums);
    System.out.println(rs);
}
public int maxProfit(int[] prices) {
    int i=0;
    int j=i+1;
    int max =0;
    while(j<prices.length){
        if(prices[i]<prices[j]){
            max += prices[j]-prices[i];
        }
        i=j;
        j++;
    }
    return max;
  }  
}

The best time to buy and sell stocks I

Suppose you have an array where the ith element is the price of a given stock on the ith day. If you can only complete a maximum of one trade (i.e. buy and sell one share of stock), design an algorithm to find the maximum profit.

Idea: The profit obtained from buying a stock on a certain day and selling it on a certain day is actually the sum of the price differences between each adjacent two days, then we are the part that requires the largest sum of price differences, that is, to find the largest adjacent sub The sum of the sequence, the problem is transformed into finding the maximum consecutive subsequence sum in the array

Assuming that dp[i] is the sum of the largest consecutive subsequences ending with i, then dp[i]=max{dp[i-1]+array[i],array[i]}, and finally dp[i] is the maximum profit .

The Best Time to Buy and Sell Stocks III

If you can only limit it twice, you can traverse from the first day to the last day of i=, and dynamically program the left and right sides to find the maximum value of the sum of both sides, and compare it with the one that has only one time.

Numbers that only appear once

Given an array of integers, all but one element appear twice. Please find this element that occurs only once.

The XOR is the same as 0, and the XOR of 0 is the number itself

class Solution {
public static void main(String [] args){
     Solution s= new Solution();
     Scanner sc= new Scanner(System.in);
     int count = sc.nextInt();
     int [] nums = new int[count];
     for(int i=0;i<count;i++){
         nums[i] = sc.nextInt();
     }
    sc.close();
    int rs = s.singleNumber(nums);
    System.out.println(rs);
}

public int singleNumber(int[] nums) {
    int num=0;
    for(int i=0;i<nums.length;i++){
        num ^=nums[i];
    }
    return num;
}
}

longest common prefix

Write a function to find the longest common prefix string in an array of strings

Idea: As long as the first string is used as a template to judge whether it is a substring of the second, if not, reduce its length by one bit from the end, and continue to judge until the substring is found or it cannot be matched

public class Solution {
 public static void main(String [] args) {
     Solution test = new Solution();
     Scanner sc = new Scanner(System.in);
     int count = sc.nextInt();
     sc.nextLine();
     String[] strs = new String[count];
     for(int j=0;j<count;j++) {
         strs[j] = sc.nextLine();
     }
     sc.close();
     String rs = test.longestCommonPrefix(strs);
     System.out.println(rs);
 }

 public String longestCommonPrefix(String[] strs) {
      String pre = strs[0];
      for(int i=0;i<strs.length;i++) {
          if(pre.length()==0) {
              break;
          }
          while(strs[i].indexOf(pre)!=0) {
              pre = pre.substring(0,pre.length()-1);
              if(pre.length()==0) break;
          }
      }
      return pre;
 }
}

count and say

Counting and saying that the sequence is a sequence of integers, the value of each item from the second item onwards is a count of the previous item, and the first five items are as follows:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

The next item can be judged by traversing the previous item. Pay attention to the details of the code.

class Solution {
public static void main(String []args) {
    Solution  test = new Solution ();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.close();
    String rs = test.countAndSay(n);
    System.out.println(rs);
}

public String countAndSay(int n) {
    List<Integer> current = new ArrayList<>();
    List<Integer> last = new ArrayList<>();
    current.add(1);
    last.add(1);
    if(n==1) {
        return current.toString().replaceAll("\\pP|\\s*","");
    }else {
        for(int i=2;i<=n;i++) {
            int k=0;
            int count =1;
            //此处不能调用clear,因为和last同一块堆内存,会清空前面last保存的内容
            current = new ArrayList<>();
            while(k<last.size()) {
                if(k==last.size()-1) {
                    break;
                }else {

                    if(last.get(k).equals(last.get(k+1))) {
                        count++;
                        k++;
                    }else {
                        current.add(count);
                        current.add(last.get(k));
                        count =1;
                        k++;
                    }
                }
            }
            current.add(count);
            current.add(last.get(k));
            last = current;
        }

        return current.toString().replaceAll("\\pP|\\s*", "");
    }
}
}

Simple breadth-first traversal

If the breadth-first search is a graph, the access status of each node needs to be recorded, and breadth-first is implemented through the queue. If the elements of each layer cannot be searched for a satisfactory solution, the queue is entered to prepare for the search of the next layer. If found, stop searching

public class BFS {
int [] node = {1,2,3,4,5,6};
int [] visted= new int[6];
int [][] v = {
        {0,1,1,1,0,0},
        {1,0,0,0,1,0},
        {1,0,0,0,0,1},
        {1,0,0,0,1,1},
        {0,1,0,1,0,0},
        {0,0,1,1,0,0}
        };
public static void main(String [] args) {
    BFS bfs = new BFS();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    bfs.visted[n-1]=1;
    bfs.searchBFS(n);
}
public void searchBFS(int n) {
    Queue<Integer> queue = new LinkedList<>();
    visted[n-1]=1;
    queue.offer(node[n-1]);

    while(!queue.isEmpty()) {
        int number = queue.poll();
        System.out.println(number);
        for(int i=0;i<6;i++) {
            if(v[i][number-1]==1) {
                if(visted[i]!=1) {
                    queue.offer(node[i]);
                    visted[i]=1;
                }
            }
        }
    }

    }
}

DFS

Depth-first search starts from the first branch of the node and continues recursively until it finishes or exceeds the depth

   public class DFS {
   int [] node = {1,2,3,4,5,6};
     int [] visted= new int[6];
     int [][] v = {
            {0,1,1,1,0,0},
            {1,0,0,0,1,0},
            {1,0,0,0,0,1},
            {1,0,0,0,1,1},
            {0,1,0,1,0,0},
            {0,0,1,1,0,0}
            };
    public static void main(String [] args) {
        DFS dfs = new DFS();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        dfs.searchDFS(n);
    }
  public void searchDFS(int n) {
      if(visted[n-1]==0) {
          visted[n-1]=1;
          System.out.println(node[n-1]);
      }else if(visted[n-1]==1){
          return;
      }
      for(int i=0;i<6;i++) {
          if(v[i][n-1]==1) {
              searchDFS(i+1);
          }
      }

  }
}

KMP algorithm

string search

For the KMP algorithm, you can refer to http://www.cnblogs.com/yjiyjige/p/3263858.html

import java.util.Scanner;

class TestKmp {
int [] next;
public static void main(String [] args){
    TestKmp s = new TestKmp();
    Scanner sc = new Scanner(System.in);
    String str1 = sc.nextLine();
    String str2 = sc.nextLine();
    sc.close();
    s.getNext(str2.toCharArray());
    int rs = s.strStr(str1,str2);
    System.out.println(rs);
}
//kmp
public int strStr(String haystack, String needle) {
    int i=0;
    int j=0;
    char [] hay = haystack.toCharArray();
    char [] need = needle.toCharArray();


    while(i<hay.length && j<need.length){
        if(j==-1||hay[i]==need[j]){
            i++;
            j++;
        }else{
            j=next[j];
        }
    }
  //注意j==length
    if(j==need.length){
        return i-j;
    }else{
        return -1;
    }
}

public void getNext(char [] child){
    next = new int[child.length];
    next[0]=-1;
    int k=-1;
    int m=0;
  //注意数组溢出问题,每次都是赋值当前索引所在后面的元素
    while(m<child.length-1){
        if(k==-1||child[k]==child[m]){
            k++;
            m++;
            next[m] = k;
        }else{
            k=next[k];
        }
    }
    for(int l=0;l<next.length;l++) System.out.println("next[j]:"+next[l]);
}

}

Find the number of pairs from an array that differ by k, excluding repeating groups

For example: 1 5 3 3 1 result=2 {1,3} {3,5}

Idea: sort the array first, then compare the previous number with the latter, exit the loop if they are equal, and continue to compare the second number with the latter. Note that if the second number is found to be equal to the first before the comparison, it will not continue. If the comparison is necessary, skip this loop and continue to compare the next number with the following

public class Main {
public static void main(String []args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int k = sc.nextInt();
    int [] nums = new int[n];
    for(int m=0;m<n;m++) {
        nums[m] = sc.nextInt();
    }
    sc.close();

    Arrays.sort(nums);

    int sum = 0;
    int i=0;
    while(i<n-1){
        if(i>0&&nums[i]==nums[i-1]) {
            i++;
            continue;
        }
        for(int j=i+1;j<n;j++) {
            if((nums[j]-nums[i])==k){
                sum++;
                i++;
                break;
            }
        }
    }

    System.out.println(sum);

}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683161&siteId=291194637