我的力扣第二题,买股票的最佳时机
题目描述:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
自己写的代码实属东拼西凑,缝缝补补;
总结:
1.while语句可以用来单纯执行 ++i 操作,直到某点停下;
2.while语句函数体里写++i,则判别语句 到 *终点前一个
;如while (i < prices.length - 1)
像这种遍历并找到符合条件的点这种问题,简直太烦了,哎
官方答案(java):
class Solution {
public int maxProfit(int[] prices) {
int i = 0;
int valley = prices[0];
int peak = prices[0];
int maxprofit = 0;
while (i < prices.length - 1) {
while (i < prices.length - 1 && prices[i] >= prices[i + 1])
i++;
valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i + 1])
i++;
peak = prices[i];
maxprofit += peak - valley;
}
return maxprofit;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-ii-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
如果是双指针的话(C++):
int maxProfit(vector<int>& prices) {
int valley=0;
int peak = 0;
int maxprofit = 0;
int sz = prices.size();
while (valley < sz - 1 && peak < sz - 1 )
{
while (valley < sz - 1 && prices[valley] >= prices[valley + 1])
{valley++;}
peak = valley;
while (peak < sz - 1 && prices[peak] <= prices[peak + 1])
{peak++;}
maxprofit += prices[peak] - prices[valley];
valley = peak;
}
return maxprofit;
};