Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Greedy Approach: Iterate through the prices and maintain buy price and maxprofit gained up until that point. -> O(N), O(1)
- int maxProfit(int[] prices, int n) {
- int buy = prices[0], max_profit = 0;
- for (int i=1; i<n; i++) {
- if (buy > prices[i]) {
- buy = prices[i];
- } else if (prices[i] - buy > max_profit) {
- max_profit = prices[i] - buy;
- }
- }
- return max_profit;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement