Similar Problems

Similar Problems not available

Capital Gainloss - Leetcode Solution

Companies:

LeetCode:  Capital Gainloss Leetcode Solution

Difficulty: Medium

Topics: database  

The Capital Gainloss problem on Leetcode is a problem that involves determining the total amount of capital gain or loss that an investor has made when buying and selling stocks. The problem statement is as follows:

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

To solve this problem, we need to iterate through the prices array and keep track of the minimum price we have seen so far. We can then calculate the profit we would make if we sold the stock on the current day, and update our maximum profit accordingly. If we encounter a price that is lower than our minimum price, we update our minimum price to be the current price. If we cannot make a profit from any of the transactions, we return 0.

Here is the detailed solution in Python:

  1. Initialize variables min_price and max_profit to the first element of the prices array, and set the index i to 1.

  2. While iterating through the prices array: a. If the current price is less than the minimum price we have seen so far, update the minimum price to be the current price. b. Otherwise, calculate the profit we would make if we sold the stock on the current day, which is the difference between the current price and the minimum price. c. If the profit is greater than the maximum profit we have seen so far, update the maximum profit to be the current profit. d. Increment the index i.

  3. Return the maximum profit.

Here is the Python code that implements the above algorithm:

def maxProfit(prices):
    if len(prices) < 2:
        return 0
    
    min_price = prices[0]
    max_profit = 0
    
    for i in range(1, len(prices)):
        if prices[i] < min_price:
            min_price = prices[i]
        else:
            current_profit = prices[i] - min_price
            if current_profit > max_profit:
                max_profit = current_profit
    
    return max_profit

Let's test the function with some sample inputs:

print(maxProfit([7,1,5,3,6,4]))  # expected output: 5
print(maxProfit([7,6,4,3,1]))    # expected output: 0

The output matches our expectations. Therefore, we can conclude that our solution is correct.

Capital Gainloss Solution Code

1