bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 2291. Maximum Profit From Trading Stocks

2291. Maximum Profit From Trading Stocks

Leetcode Solutions

Dynamic Programming -/ Knapsack Approach

  1. Initialize a 1D array dp of length budget + 1 with all elements set to 0.
  2. Iterate over each stock i from 0 to n - 1.
  3. For each stock, iterate over the budget j from budget down to the cost of the current stock present[i].
  4. If buying the stock is profitable (future[i] > present[i]), update dp[j] to be the maximum of dp[j] and dp[j - present[i]] + future[i] - present[i].
  5. After iterating through all stocks, return dp[budget] as the maximum profit.
UML Thumbnail

Greedy Approach with Sorting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...