[LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)

本文介绍了一种算法,用于计算给定股票价格序列的最大可能利润,允许进行多次买入卖出操作,但不能同时持有股票。通过遍历数组并累加升序差值来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

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).

题目大意:
有一个数组,第i个元素是第i天给定股票的价格。
设计一个算法来找到最大的利润。 你可以根据需要完成尽可能多的交易(即,买一次卖一次,多次出售股票)。 但是,您可能不会同时从事多个交易(即,您必须在再次购买之前出售股票)

思路:
- 遍历数组
- 只要后面价格高于前面,差值就加到利润上
- 最终得到最大利润
- 例如:{2, 8, 6, 9} 利润最高是9,Profit = (8-2) + (9-6)
- 例如:{5, 1, 2, 4, 6} 利润最高是5,Profit = (2-1) + (4-2)+ (6-4)

代码如下:

#include <iostream>
#include <vector>
using namespace std;
class Solution {//求股票最大收益,每次只能持有一股,卖必须在买之后
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0)
            return 0;
        int MaxProfit = 0;
        for(int i=0; i< prices.size()-1; i++){//i+1 最大为n-1,n为数组长度
            if(prices[i] < prices[i+1])
                MaxProfit += prices[i+1] - prices[i];//更新最大利益
        }
        /*
        for(int i=1; i< prices.size(); i++){
            if(prices[i] > prices[i-1])
                MaxProfit += prices[i] - prices[i-1];//更新最大利益
        }
        */
        return MaxProfit;
    }
};
int main()
{
    Solution a;
    int A[4] = {2, 8, 6, 9};
    vector<int> prices(A, A+4);
    cout << "股票近期行情:";
    for(int i=0; i< prices.size(); i++){
            cout << prices[i] << " ";
    }
    cout << endl;
    cout << "最大收益:" << a.maxProfit(prices) << endl;
    return 0;
}

点击查看LeetCode官方解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值