LeetCode 1393: Capital Gain/Loss Solution

Master LeetCode problem 1393 (Capital Gain/Loss), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1393. Capital Gain/Loss

Medium

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the given table of stock transactions and calculate the capital gains or losses for each stock. We can achieve this by maintaining a hashmap to keep track of the total capital gain/loss for each stock. We iterate through the transactions and update the hashmap accordingly.

  1. Initialize a hashmap to store the total capital gain/loss for each stock.
  2. Iterate through the stock transactions:
    • For each "Buy" operation, calculate the difference between the buying price and add it to the hashmap.
    • For each "Sell" operation, calculate the difference between the selling price and subtract it from the hashmap.
  3. Return the result table with stock names and their capital gain/loss.

Time Complexity: O(n) where n is the number of transactions in the table. Space Complexity: O(n) for the hashmap to store the capital gain/loss for each stock.

:

Solution Code

# Write your Java solution here
SELECT stock_name,
    SUM(CASE WHEN operation = 'Sell' THEN price * -1 ELSE price END) AS capital_gain_loss
FROM Stocks
GROUP BY stock_name

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1393 (Capital Gain/Loss)?

This page provides optimized solutions for LeetCode problem 1393 (Capital Gain/Loss) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1393 (Capital Gain/Loss)?

The time complexity for LeetCode 1393 (Capital Gain/Loss) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1393 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1393 in Java, C++, or Python.

Back to LeetCode Solutions