Beats 100% time , Beats 100% space: Greedy TreeMap
\n\n# Intution\n\nWe create a TreeMap in which the key is an element of the grid and the value is a set of rowIndexes that had the element.\n\nWe start from the
![image.png](https://assets.leetcode.com/users/images/2959b070-4f16-4f12-84b2-206afa91278a_1725167093.7640224.png)\n\n# Intution\n\nWe create a TreeMap in which the key is an element of the grid and the value is a set of rowIndexes that had the element.\n\nWe start from the biggest number and keep going down. We also keep track of the visited  rowIndexes. If the rowIndex for the current  number is not visited, we can include that number. Otherwise, we skip it.\n\nPlease let me know if you\'d like a detailed explanation or if you have any questions.\n\n# Time Complexity\n\nIn general, it\'s O(row * uniqueElements)\n\nIf the number of unique elements is approximately equal to the number of columns, the time complexity is equal to the input size\n \n\n# Code\n```java [] \n  TreeMap<Integer, Set<Integer>> treeMap = new TreeMap<>();\n\n  public int maxScore(List<List<Integer>> grid) {\n    createTreeMap(grid);\n    Integer last = treeMap.lastKey();\n    return getMax(last + 1, new HashSet<>());\n  }\n\n  private void createTreeMap(List<List<Integer>> grid) {\n    for (int rowIndex = 0; rowIndex < grid.size(); rowIndex++) {\n      List<Integer> list = grid.get(rowIndex);\n      for (int columnIndex = 0; columnIndex < list.size(); columnIndex++) {\n        int element = list.get(columnIndex);\n        if (!treeMap.containsKey(element))\n          treeMap.put(element, new HashSet<>());\n\n        treeMap.get(element).add(rowIndex);\n      }\n    }\n  }\n\n  private int getMax(Integer biggerNumber, Set<Integer> visited) {\n    Integer currentNumber = treeMap.lowerKey(biggerNumber);\n    if (currentNumber == null) {\n      return 0;\n    }\n    Set<Integer> rowIndexesSet = treeMap.get(currentNumber);\n    boolean hadValidIndex = false;\n    int max = 0;\n    for (int rowIndex : rowIndexesSet) {\n      if (visited.contains(rowIndex)) {\n        continue;\n      }\n      hadValidIndex = true;\n      visited.add(rowIndex);\n      int maxSumOfLowerNumbers = getMax(currentNumber, visited);\n      max = Math.max(max, maxSumOfLowerNumbers);\n      visited.remove(rowIndex);\n    }\n    if (hadValidIndex) {\n      return max + currentNumber;\n    }\n    return getMax(currentNumber, visited);\n  }\n```
['Java']