Ritu Singh
Summary:
Here we will learn to code in the scenario where the app can automatically buy the share at the lowest price and sell them on maximum profit.
Solution:
Explanation:
The maxProfit method takes two parameters: n, the number of elements in the price array, and price, an array containing the prices of stocks on different days.
It first checks if the number of elements in the price array is less than or equal to 1. If so, it returns 0, as there's no opportunity to make a profit with only one or zero elements.
Two arrays leftProfit and rightProfit of size n are initialized to store the maximum profit achievable by buying and selling stocks on the left and right sides of the array, respectively.
The algorithm then calculates the maximum profit that can be made by buying and selling stocks only on the left side of the array (leftProfit). It iterates through the price array, updating the minimum price (minPrice) encountered so far and calculating the maximum profit at each step.
Similarly, it calculates the maximum profit that can be made by buying and selling stocks only on the right side of the array (rightProfit). It iterates through the price array in reverse order, updating the maximum price (maxPrice) encountered so far and calculating the maximum profit at each step.
After computing the maximum profit on both sides of the array, it calculates the maximum combined profit by summing up the corresponding profits from the leftProfit and rightProfit arrays for each day.
Finally, it returns the maximum combined profit.
Overall, this algorithm effectively breaks down the problem of finding the maximum profit into two subproblems (calculating maximum profit on the left and right sides) and then combines the solutions to find the overall maximum profit.
Suggested blogs:
>How to route between different components in React.js?
>How to save Python yaml and load a nested class?-Python
>How to send multiple HTML form fields to PHP arrays via Ajax?
>What is data binding in Angular?
>What is microservice architecture, and why is it better than monolithic architecture?
>What makes Python 'flow' with HTML nicely as compared to PHP?
>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?
>Creating custom required rule - Laravel validation