121. Best Time to Buy and Sell Stock
You are given an 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.
Example: 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Example: 2
Input: [7,6,4,3,1]
Output: 0
Constraints:
- 1 <= prices.length <= 10 ^ 5
- 0 <= prices[i] <= 10 ^ 4
Important observation:
- Let's say the array is of size N with elements from [1, N].
- Let's say we have bought a stock at index i, then to maximize our profit, we will sell it at the point from [i + 1, N], where the value is maximum.
- So by doing it for every individual i, we will have our answer.
Full Code (Java):
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
// creating an array to store the maximum value
// from [i, n - 1]
int[] max = new int[n];
max[n - 1] = prices[n - 1];
// storing max value from index [i, n - 1]
// 0 - based indexing
for(int i = n - 2; i >= 0; i--) {
max[i] = Math.max(prices[i], max[i + 1]);
}
// computing our final answer
int ans = 0;
for(int i = 0; i < n - 1; i++) {
ans = Math.max(ans, max[i + 1] - prices[i]);
}
return ans;
}
}
Comments
Post a Comment
If you have any queries or need solution for any problem, please let me know.