买卖股票的最佳时机 II (Best Time to Buy and Sell Stock II)

 

思路:

// @Title: 买卖股票的最佳时机 II (Best Time to Buy and Sell Stock II)
// @Author: qisiii
// @Date: 2024-09-22 17:34:18
// @Runtime: 0 ms
// @Memory: 44.5 MB
// @comment: 
// @flag: 
class Solution {
    public int maxProfit(int[] prices) {
        int sum = 0;
        int old = -1;
        for (int i = 0; i < prices.length; i++) {
            //由于可以保证购买的时候一定是低价,因此每一天都要先把历史持有的卖掉
            if (old >=0) {
                sum = sum + (prices[i] - old);
                old = -1;
            }
            //判断当前是否还是低价,如果是就买
            if (i < prices.length - 1 && prices[i] < prices[i + 1]) {
                old = prices[i];
            }
        }
        return sum;
    }
}

+++ title = “买卖股票的最佳时机 II (Best Time to Buy and Sell Stock II)” draft = false +++

思路:

// @Title: 买卖股票的最佳时机 II (Best Time to Buy and Sell Stock II)
// @Author: qisiii
// @Date: 2022-02-26 12:42:57
// @Runtime: 1 ms
// @Memory: 41.1 MB
// @comment: 
// @flag: 
class Solution {
    public int maxProfit(int[] prices) {
        int sum=0;
        for(int i=1;i<prices.length;i++){
           int temp= prices[i]-prices[i-1];
            if(temp>0){
                sum=temp+sum;
            }
        }
        return sum;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18