Untitled
unknown
java
2 years ago
4.6 kB
9
Indexable
String[] solution(String[][] queries) { HashMap<String, Integer> cuentas = new HashMap<>(); String[] result = new String[queries.length]; Integer countS = 1; class Spends implements Comparable<Spends>{ String account; Integer amount; public Spends(String account, Integer amount) { this.account = account; this.amount = amount; } @Override public int compareTo(Spends spends2) { Integer resta = spends2.amount - this.amount; if (resta == 0) { return this.account.compareTo(spends2.account); } return resta; } public String toString() { return String.format("%s(%d)", this.account, this.amount); } } HashMap<String, Integer> spends = new HashMap<>(); HashMap<Integer, Queue<Spends>> scheduleP = new HashMap<>(); for (int i = 0; i< queries.length; i++) { String[] stm = queries[i]; String action = stm[0]; String accountId = stm[2]; switch(action){ case "CREATE_ACCOUNT": if(cuentas.containsKey(accountId)){ result[i] = "false"; } else { cuentas.put(accountId, 0); result[i] = "true"; spends.put(accountId, 0); } break; case "DEPOSIT": if(cuentas.containsKey(accountId) && "non-existing".compareTo(accountId) != 0){ Integer currentAmount = cuentas.get(accountId); currentAmount = currentAmount + Integer.valueOf(stm[3]); cuentas.put(accountId, currentAmount); result[i] = currentAmount.toString(); } else { result[i] = ""; } break; case "TRANSFER": String target = stm[3]; if(!cuentas.containsKey(accountId) || !cuentas.containsKey(target) || accountId.compareTo(target) == 0) { result[i] = ""; } else { Integer currentAmount = cuentas.get(accountId); Integer transfer = Integer.valueOf(stm[4]); currentAmount = currentAmount - transfer; if(currentAmount<0) { result[i] = ""; } else { cuentas.put(accountId, currentAmount); Integer targetAmount = cuentas.get(target); targetAmount = targetAmount + transfer; cuentas.put(target, targetAmount); result[i] = currentAmount.toString(); Integer currentSpend = spends.get(accountId); spends.put(accountId, currentSpend + transfer); } } break; case "TOP_SPENDERS": List<Spends> lista = new ArrayList<>(); spends.keySet().forEach(k -> { lista.add(new Spends(k, spends.get(k))); }); Collections.sort(lista); Integer n = Integer.valueOf(stm[2]); if(n > lista.size()) { n = lista.size(); } result[i] = lista.subList(0, n).toString().replace("[", "").replace("]", ""); break; case "SCHEDULE_PAYMENT": String id = "payment" + countS; countS++; result[i] = id; Integer time = Integer.valueOf(stm[1]) + Integer.valueOf(stm[4]); Integer amount = Integer.valueOf(stm[3]); if(scheduleP.containsKey(time)) { Queue queue = scheduleP.get(time); queue.add(new Spends(accountId, amount)); } break; case "CANCEL_PAYMENT": result[i] = "true"; break; } } return result; }
Editor is loading...