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;
}
相关推荐
无限码力7 分钟前
拼多多 春招&秋招 笔试真题题库目录|笔试题库 + 算法考点详解
算法·pdd笔试真题·pdd笔试真题题解·拼多多春招笔试真题·拼多多秋招笔试真题·拼多多笔试真题题解
Dovis(誓平步青云)10 分钟前
同一条路线在手机和平板上怎样换一种排版
android·开发语言·数据库·智能手机·音视频
loong_XL11 分钟前
Windows WSL2 Ubuntu 搭建 Xvfb 虚拟桌面环境,完美支持多 Agent 隔离
linux·windows·ubuntu
大熊背12 分钟前
树莓派 libcamera IPA 框架解析
linux·ipa·isppipeline
春风解人意15 分钟前
从零开始学习嵌入式P30----进程间的通信
c语言·学习
OPEN-F15 分钟前
C++进阶教程:文件流与字符串流
开发语言·c++·算法
2601_9669496519 分钟前
9:25-9:30 如何获取 A 股开盘基准价?QuantDash Python SDK 实战初始化量化策略状态
开发语言·人工智能·python·量化·quantdash·量化数据源
Horn Still Sounds20 分钟前
Linux进程间通信:信号、消息队列、共享内存完整笔记
linux·网络·笔记
拂拉氏21 分钟前
【知识讲解】 Linux进程的认识与创建
linux·进程
Java小白笔记22 分钟前
Java中fixedDealy和fixedRate的区别是什么?
java·开发语言