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,1]Output: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;
}
相关推荐
chenzhou__2 分钟前
LinuxC语言并发程序笔记(第二十天)
linux·c语言·笔记·学习
会飞的土拨鼠呀9 分钟前
运维工程师需要具备哪些技能
linux·运维·ubuntu
立志成为大牛的小牛12 分钟前
数据结构——四十九、B树的删除与插入
数据结构·学习·程序人生·考研·算法
5***o50017 分钟前
JavaScript云原生
开发语言·javascript·云原生
爱吃西瓜的小菜鸡18 分钟前
【Java】面向对象基础——继承 + 封装基础题
java·开发语言
心疼你的一切22 分钟前
Unity开发Rokid应用之离线语音指令交互模型
android·开发语言·unity·游戏引擎·交互·lucene
N***738522 分钟前
JavaScript物联网案例
开发语言·javascript·物联网
IT方大同30 分钟前
C语言的组成部分
c语言·开发语言
BINGCHN31 分钟前
流量分析进阶(一):RCTF2025-Shadows of Asgard
开发语言·python
BestOrNothing_201537 分钟前
【C++基础】Day 4:关键字之 new、malloc、constexpr、const、extern及static
c++·八股文·static·extern·new与malloc·constexpr与const