xxxxxxxxxx
int maxProfit(vector<int>& prices) {
int maxProfit=0;
int left=0;
int right=left+1;
while(right<prices.size()){
if(prices[left]>prices[right]){
left=right;
right++;
}
else{
maxProfit=max(maxProfit,prices[right]-prices[left]);
right++;
}
}
return maxProfit;
}
xxxxxxxxxx
let prices = [7, 4, 5, 6, 7, 1, 2, 4, 2, 3, 4, 5, 6, 7, 2, 3]
// Two pointers and flexible-size sliding window technique
// Memory: O(1), Time: O(n)
const maxProfit = function (prices) {
let l = 0
let r = 1
let profit = 0
let min = Number.POSITIVE_INFINITY
let max = Number.NEGATIVE_INFINITY
while (r < prices.length) {
if (min > prices[l]) {
min = prices[l]
max = Number.NEGATIVE_INFINITY
}
if (max < prices[r]) {
max = prices[r]
}
if (profit < max - min) {
profit = max - min
}
console.log(prices[l], prices[r], 'profit: ', profit)
if (prices[l] <= prices[r]) {
r++
}
if (prices[r - 1] > prices[r]) {
l = r
r++
}
}
return profit
}
console.log(maxProfit(prices))
// [Log]:
4 5 profit: 1
4 6 profit: 2
4 7 profit: 3
1 2 profit: 3
1 4 profit: 3
2 3 profit: 3
2 4 profit: 3
2 5 profit: 4
2 6 profit: 5
2 7 profit: 6
2 3 profit: 6
6
xxxxxxxxxx
public class Buy_Sell_Stocks {
public static int buy_sell_stocks(int[] prices) {
int buying_price = Integer.MAX_VALUE;
int Max_Profit = 0;
for (int i = 0; i < prices.length; i++) {
if (buying_price < prices[i]) {
int profit = prices[i] - buying_price;
Max_Profit = Math.max(Max_Profit, profit);
} else {
buying_price = prices[i];
}
}
return Max_Profit;
}
public static void main(String[] args) {
int[] arr = {7, 1, 5, 3, 6, 4};
System.out.println(buy_sell_stocks(arr));
}
}