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;
}
相关推荐
奇妙之二进制2 分钟前
机器人导航路径规划算法入门(6)Dijkstra(迪杰斯特拉)算法深入解析
算法·导航
重生的黑客2 分钟前
Qt 常用控件精讲(1):QWidget 核心属性全解 —— 从 geometry 到 qrc 与 QSS
c++·qt·qwidget·qss·常用控件
鸠摩智首席音效师7 分钟前
Linux /etc/nsswitch.conf 文件有什么作用 ?
linux
东城居士16 分钟前
理解pinctrl和gpio子系统驱动
linux·嵌入式系统
Hespethorn16 分钟前
取 `X-Forwarded-For` 首段做频控 key,等于把限流开关交给了调用方
c++
米糕闯编程17 分钟前
鱼香ros2(七)功能包组织C++节点
c++·ros2·cmakelists
H_oRIZoN_22 分钟前
Linux入门DAY43 ARM 架构基础、寄存器、大小端、异常向量、交叉编译
linux·arm·linux应用编程
Niuguangshuo23 分钟前
论文解读:Qwen2-Audio,阿里的通用音频语言模型
算法·音视频·语音识别
Y38153266233 分钟前
SERP 数据清洗实战:字段标准化、日期解析与去重键
开发语言·数据库·python·python数据库
汉克老师39 分钟前
GESP2026年9月认证C++四级( 第三部分编程题(1、新汉诺塔))精讲
c++·gesp·小学生·学c++编程