Skip to content

Commit bb5c543

Browse files
authored
Update 0122-best-time-to-buy-sell-stock-II.md
1 parent d3f3bc3 commit bb5c543

File tree

1 file changed

+144
-0
lines changed

1 file changed

+144
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,145 @@
1+
---
2+
id: best-time-to-buy-sell-stock-II
3+
title: Best Time to Buy and Sell Stock Solution -II
4+
sidebar_label: 0122 Best-Time-to-Buy-and-Sell-Stock -II
5+
tags:
6+
- Best Time to Buy and Sell Stock
17

8+
description: "This is a solution to the Best Time to Buy and Sell Stock problem -II on LeetCode."
9+
---
10+
11+
12+
## Problem Description
13+
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
14+
15+
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
16+
17+
Find and return the maximum profit you can achieve.
18+
19+
20+
### Examples
21+
22+
**Example 1:**
23+
24+
```plaintext
25+
Input: prices = [7,1,5,3,6,4]
26+
Output: 7
27+
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
28+
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
29+
Total profit is 4 + 3 = 7.
30+
```
31+
32+
**Example 2:**
33+
34+
```plaintext
35+
Input: prices = [1,2,3,4,5]
36+
Output: 4
37+
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
38+
Total profit is 4.
39+
```
40+
41+
**Example 3:**
42+
```plaintext
43+
Input: prices = [7,6,4,3,1]
44+
Output: 0
45+
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
46+
```
47+
48+
### Constraints
49+
50+
- `1 <= prices.length <= 3 * 10^4`
51+
- `0 <= prices[i] <= 10^4`
52+
53+
---
54+
55+
## Solution for Best Time to Buy and Sell Stock Problem
56+
### Intuition
57+
In the given problem, we are provided with an array named "prices," where prices[i] represents the current price of a stock on day i. The task is to determine the maximum profit that can be achieved from selling the stock.
58+
59+
### Approach
60+
- To solve this question we will use Greedy Algorithm.
61+
62+
- Now if you don't know anything about Greedy algorithm here is the small explanation of the Greedy.
63+
64+
- Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. In these algorithms, decisions are made based on the information available at the current moment without considering the consequences of these decisions in the future. The key idea is to select the best possible choice at each step, leading to a solution that may not always be the most optimal but is often good enough for many problems.
65+
66+
### Code Explanation
67+
- Variable Initialization:
68+
69+
- max is initialized to 0. This variable will accumulate the maximum profit throughout the iteration.
70+
- start is initialized to prices[0], the price of the stock on the first day. This variable represents the buying price of the stock.
71+
- len is initialized to prices.length, the length of the prices array, representing the total number of days.
72+
Iteration: A for loop iterates through the prices array starting from the second element (i = 1) to the end of the array (i < len). This loop is used to calculate the profit for each transaction.
73+
74+
#### Profit Calculation:
75+
76+
- Within the loop, there's an if statement checking if the current price (prices[i]) is greater than the buying price (start). If true, it indicates a potential profit opportunity.
77+
- The difference between the current price and the buying price (prices[i] - start) is calculated and added to max. This step simulates selling the stock bought at start price, capturing the profit, and then considering the current price as a new buying price for potential future transactions.
78+
- Regardless of whether a profit was made or not, the start is updated to the current price (prices[i]). This step prepares for the next iteration, considering the current day's price as the new buying price.
79+
- Return Statement: After the loop finishes executing, the method returns the accumulated max value, which represents the maximum profit that could have been achieved based on the given stock prices.
80+
81+
82+
### Code in Different languages
83+
#### Code in C++
84+
85+
```c++
86+
class Solution {
87+
public:
88+
int maxProfit(vector<int>& prices) {
89+
int max = 0;
90+
int start = prices[0];
91+
int len = prices.size();
92+
for(int i = 1;i<len; i++){
93+
if(start < prices[i]){
94+
max += prices[i] - start;
95+
}
96+
start = prices[i];
97+
}
98+
return max;
99+
}
100+
};
101+
```
102+
103+
#### Code in Python
104+
```python
105+
class Solution(object):
106+
def maxProfit(self, prices):
107+
"""
108+
:type prices: List[int]
109+
:rtype: int
110+
"""
111+
max = 0
112+
start = prices[0]
113+
len1 = len(prices)
114+
for i in range(0 , len1):
115+
if start < prices[i]:
116+
max += prices[i] - start
117+
start = prices[i]
118+
return max
119+
```
120+
121+
122+
#### Code in Java
123+
```Java
124+
class Solution {
125+
public int maxProfit(int[] prices) {
126+
int max = 0;
127+
int start = prices[0];
128+
int len = prices.length;
129+
for(int i = 1;i<len; i++){
130+
if(start < prices[i]) max += prices[i] - start;
131+
start = prices[i];
132+
}
133+
return max;
134+
}
135+
}
136+
```
137+
138+
139+
140+
141+
### Complexity Analiysis
142+
143+
- Time complexity: `O(N)`
144+
- Space complexity: `O(1)`
145+
---

0 commit comments

Comments
 (0)