C语言刷题 LeetCode 30天挑战 (五)贪心算法

//Best Time to Buy and Sell Stockl

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

//Desian an algorithm to find the maximum profit, You mav complete as many transactions as you like lle..

//buy one and sell one share othe stock multiple times)

//Note: You may not engage in multiple transactions at the same time (i.., you must sell the stock before you buy again

//Example 1:

//Input:7,1,5,3,6,4

//Output:7

//Explanation: Buyon day2(price=1)and sell on day 3(price = 5),profit = 5-1 = 4.

//Then buy on day4(price=3)and sell on day5(price =6),profit =6-3 = 3.

//Example 2:

//Input:1,2,3,4,5

//0utput:4

//Explanation: Buyon day1(price =1)and sell on day 5(price = 5), profit = 5-1 = 4.

//Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are

//engaging multiple transactions at the same time. You must sell before buying again.

//Example 3:

//Input:7,6,4,3,1Output:0

//Explanation:In this ase,no transaction is done, i.e. max profit = 0.

cpp 复制代码
#include <stdio.h>
//贪心算法
int maxProfit(int* prices, int pricesSize) {
    int maxProfit = 0;

    for (int i = 1; i < pricesSize; ++i){
        // 只要今天的价格高于昨天的价格,就可以获利
        if (prices[i] > prices[i - 1]) {
            maxProfit += prices[i] - prices[i - 1];
        }
    }

    return maxProfit;
}

int main() {
    // 示例输入
    int prices1[] = {7, 1, 5, 3, 6, 4};
    int prices2[] = {1, 2, 3, 4, 5};
    int prices3[] = {7, 6, 4, 3, 1};

    printf("Example 1: Max Profit = %d\n", maxProfit(prices1, 6)); // 输出: 7
    printf("Example 2: Max Profit = %d\n", maxProfit(prices2, 5)); // 输出: 4
    printf("Example 3: Max Profit = %d\n", maxProfit(prices3, 5)); // 输出: 0

    return 0;
}
相关推荐
benchmark_cc6 分钟前
一次获取多只股票实时行情:QuantDash `quotes.get(symbols=[...])` 批量快照
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
geovindu10 分钟前
python: PCA
开发语言·后端·python·算法
Matt Feng18 分钟前
STM32多路SWD烧录:并行下载与5类连接故障排查
c语言·stm32·单片机·嵌入式硬件
DeskUI~~22 分钟前
8.4M,我把 Linux 变成了一块“磁盘”
linux·运维·服务器
少陽君30 分钟前
如何在 PVE 中下载并导入 Ubuntu 24.04 Server 云镜像
linux·数据库·ubuntu
无足鸟ICT37 分钟前
【RHCA+】_proc_pid_environ
linux·运维·服务器
guizhoumen1 小时前
PageAdmin开源网站无障碍/适老化工具条插件-让网站“看得清、听得懂“
c++·mfc
__万波__1 小时前
嵌入式存储技术--1.Flash物理存储
java·开发语言
凯程序猿1号1 小时前
基于射线法与球面外积的WGS84电子围栏点在多边形内判定及边界容差算法
算法·电脑
Chen_harmony1 小时前
十六、ALV树
开发语言·c++