Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1831. Maximum Transaction Each Day - Leetcode Solution

Code Implementation

from collections import defaultdict

def maximumTransactionEachDay(transactions):
    # transactions: List[List[int]] where each transaction is [transaction_id, user_id, amount, date]
    # Output: List[List[int]] where each row is [date, max_amount]
    max_by_date = defaultdict(int)
    for t in transactions:
        date = t[3]
        amount = t[2]
        if amount > max_by_date[date]:
            max_by_date[date] = amount
    result = []
    for date in sorted(max_by_date):
        result.append([date, max_by_date[date]])
    return result
    
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<vector<string>> maximumTransactionEachDay(vector<vector<string>>& transactions) {
    unordered_map<string, int> maxByDate;
    for (const auto& t : transactions) {
        string date = t[3];
        int amount = stoi(t[2]);
        if (maxByDate.find(date) == maxByDate.end() || amount > maxByDate[date]) {
            maxByDate[date] = amount;
        }
    }
    vector<pair<string, int>> temp;
    for (const auto& p : maxByDate) {
        temp.push_back({p.first, p.second});
    }
    sort(temp.begin(), temp.end());
    vector<vector<string>> result;
    for (const auto& p : temp) {
        result.push_back({p.first, to_string(p.second)});
    }
    return result;
}
    
import java.util.*;

public class Solution {
    public List<List<String>> maximumTransactionEachDay(List<List<String>> transactions) {
        Map<String, Integer> maxByDate = new HashMap<>();
        for (List<String> t : transactions) {
            String date = t.get(3);
            int amount = Integer.parseInt(t.get(2));
            maxByDate.put(date, Math.max(maxByDate.getOrDefault(date, 0), amount));
        }
        List<String> dates = new ArrayList<>(maxByDate.keySet());
        Collections.sort(dates);
        List<List<String>> result = new ArrayList<>();
        for (String date : dates) {
            result.add(Arrays.asList(date, String.valueOf(maxByDate.get(date))));
        }
        return result;
    }
}
    
function maximumTransactionEachDay(transactions) {
    // transactions: Array of [transaction_id, user_id, amount, date]
    const maxByDate = {};
    for (const t of transactions) {
        const date = t[3];
        const amount = Number(t[2]);
        if (!(date in maxByDate) || amount > maxByDate[date]) {
            maxByDate[date] = amount;
        }
    }
    const dates = Object.keys(maxByDate).sort();
    const result = [];
    for (const date of dates) {
        result.push([date, maxByDate[date]]);
    }
    return result;
}
    

Problem Description

You are given a list of financial transactions, where each transaction is represented as a list containing four elements: [transaction_id, user_id, amount, date]. Your task is to find, for each unique date, the maximum amount that was transacted on that day.

The output should be a list of lists, where each inner list contains the date and the corresponding maximum amount for that day. The output should be sorted in ascending order by date.

  • Each transaction_id and user_id is unique per transaction, but you may ignore them for this problem.
  • There may be multiple transactions per day, but you should only report the highest amount for each date.
  • Do not reuse or sum amounts; only the maximum per day is needed.
  • Assume there is always at least one transaction per date.

Thought Process

At first, you might think about iterating through all transactions and, for each date, checking all transactions with that date to find the maximum. However, this would be inefficient because you would be scanning the list multiple times for each date.

Instead, a better approach is to use a data structure that allows you to keep track of the maximum amount for each date as you process each transaction. By doing this in a single pass, you avoid redundant work and make your solution much more efficient.

This is a classic "group by" and "aggregate" problem, which is often solved using hash maps (dictionaries) in most programming languages.

Solution Approach

Let's break down the solution step by step:

  1. Initialize a Hash Map:
    • Create an empty hash map (or dictionary) where the keys are dates and the values are the maximum amount seen so far for that date.
  2. Iterate Through Transactions:
    • For each transaction, extract the date and amount.
    • If the date is not in the hash map, add it with the current amount.
    • If the date is already in the hash map, compare the current amount with the stored value and update if the current amount is higher.
  3. Prepare the Result:
    • After processing all transactions, iterate over the keys (dates) in the hash map.
    • Sort the dates in ascending order to meet the output requirement.
    • For each date, create a list or array with the date and the corresponding maximum amount.
  4. Return the Result:
    • Return the list of lists/arrays as the final answer.

This approach ensures that each transaction is processed only once, and the maximum for each date is always up-to-date.

Example Walkthrough

Let's walk through an example. Suppose the input transactions are:

  • [101, 5, 200, "2023-05-01"]
  • [102, 7, 350, "2023-05-01"]
  • [103, 4, 180, "2023-05-02"]
  • [104, 2, 400, "2023-05-01"]
  • [105, 1, 220, "2023-05-02"]

Step-by-step:

  1. Start with an empty hash map: {}
  2. Process first transaction: date = "2023-05-01", amount = 200
    Update map: {"2023-05-01": 200}
  3. Process second transaction: date = "2023-05-01", amount = 350
    350 > 200, so update: {"2023-05-01": 350}
  4. Process third transaction: date = "2023-05-02", amount = 180
    New date, add: {"2023-05-01": 350, "2023-05-02": 180}
  5. Process fourth transaction: date = "2023-05-01", amount = 400
    400 > 350, so update: {"2023-05-01": 400, "2023-05-02": 180}
  6. Process fifth transaction: date = "2023-05-02", amount = 220
    220 > 180, so update: {"2023-05-01": 400, "2023-05-02": 220}

Sort the dates: ["2023-05-01", "2023-05-02"]
Final output: [["2023-05-01", 400], ["2023-05-02", 220]]

Time and Space Complexity

  • Brute-force approach:
    • For each unique date, scan all transactions to find the maximum. If there are n transactions and d unique dates, this is O(n * d).
  • Optimized approach (hash map):
    • We process each transaction once: O(n).
    • Sorting the dates at the end costs O(d log d), where d is the number of unique dates.
    • Total time complexity: O(n + d log d).
    • Space complexity: O(d) for the hash map, as we store one value per unique date.

Summary

This problem is a classic example of grouping and aggregation, efficiently solved using a hash map to track the maximum value for each group (date). By processing each transaction only once and updating the maximum as we go, we achieve both clarity and efficiency. The final sorting step ensures the output is in the required order. This approach is elegant because it leverages the right data structures for the job and avoids unnecessary repeated work.