121. Best Time to Buy and Sell Stock买卖股票12

时间:2022-04-10 08:47:26

[抄题]:

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Input: [7, 1, 5, 3, 6, 4]
Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

[一句话思路]:贪心算法。不要用数组i,j角标,直接用min, profit表示价格,更方便。

[画图]:

[一刷]:

min, profit都记得要初始化

[总结]:

[复杂度]:

n/1

[英文数据结构]:

Range Queries

[其他解法]:

[题目变变变]:

maximum subarray最大求和子数组

class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0 || prices == null) {
return 0;
} int min = Integer.MAX_VALUE;
int profit = 0;
for (int i = 0; i < prices.length; i++) {
min = min < prices[i] ? min : prices[i];
profit = (prices[i] - min) > profit ? prices[i] - min : profit;
} return profit;
}
}

[抄题]:

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).可以买卖无数次,但是必须先卖后买。

[一句话思路]:

股票profit或者数组sum只有一个时,用贪心算法,容易定义。

股票profit是很多利润的累加时,用数组i,j角标来叠加。因为只要上涨就要卖出,攫取利润。

[画图]:

[一刷]:

由于出现了prices[i + 1], 循环体的上界要减1,为for (int i = 0; i < prices.length - 1; i++)

[总结]:

[复杂度]:

[英文数据结构]:

[其他解法]:

[题目变变变]:

class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0 || prices == null) {
return 0;
} int diff = 0;
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i + 1] - prices[i] > 0) {
diff += prices[i + 1] - prices[i];
}
} return diff;
}
}