fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. String s1 = "zyxwv";
  14. String s2 = "edcba";
  15. int[][]dp = new int[s1.length()+1][s2.length()+1];
  16. for(int[] row: dp){
  17. Arrays.fill(row,-1);
  18. }
  19.  
  20. System.out.println(solve(0,0,s1.toCharArray(),s2.toCharArray(), dp));
  21. }
  22.  
  23. public static int solve(int i, int j, char[] str1, char[] str2, int[][]dp ){
  24.  
  25. if(i== str1.length && j == str2.length) return 0;
  26. if(dp[i][j] != -1) return dp[i][j];
  27.  
  28. int ans = Integer.MAX_VALUE;
  29.  
  30. if(i<str1.length ){
  31. char ch = str1[i];
  32. int intCfts = checkConflicts(str1, i, ch);
  33. int newCfts = checkConflicts(str2, j, ch);
  34. ans = Math.min(ans, intCfts+newCfts+solve(i+1,j, str1, str2, dp));
  35. }
  36.  
  37. if(j<str2.length ){
  38. char ch = str2[j];
  39. int intCfts = checkConflicts(str2, j, ch);
  40. int newCfts = checkConflicts(str1, i, ch);
  41. ans = Math.min(ans, intCfts+newCfts+solve(i,j+1,str1, str2, dp));
  42.  
  43. }
  44.  
  45. return dp[i][j] = ans;
  46.  
  47. }
  48. public static int checkConflicts(char[] str, int index, char ch){
  49. int cnt = 0;
  50. for(int i = index; i< str.length; i++){
  51. if(str[i]-'a' < ch-'a') cnt++;
  52. }
  53. return cnt;
  54. }
  55. }
Success #stdin #stdout 0.12s 54632KB
stdin
Standard input is empty
stdout
20