力扣:买股票的最佳时机

我的力扣第二题,买股票的最佳时机
题目描述:

给定一个数组,它的第 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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值