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;
}
相关推荐
我是咸鱼不闲呀3 分钟前
力扣Hot100系列21(Java)——[多维动态规划]总结(不同路径,最小路径和,最长回文子串,最长公共子序列, 编辑距离)
java·leetcode·动态规划
我命由我123453 分钟前
Element Plus 2.2.27 的单选框 Radio 组件,选中一个选项后,全部选项都变为选中状态
开发语言·前端·javascript·html·ecmascript·html5·js
lihao lihao6 分钟前
二分查找
java·数据结构·算法
Albert Edison6 分钟前
【C++11】可变参数模板
java·开发语言·c++
WolfGang0073218 分钟前
代码随想录算法训练营 Day15 | 二叉树 part05
数据结构·算法
sheeta19989 分钟前
LeetCode 每日一题笔记 2025.03.20 3567.子矩阵的最小绝对差
笔记·leetcode·矩阵
代码栈上的思考9 分钟前
消息队列持久化:文件存储设计与实现全解析
java·前端·算法
cyber_两只龙宝9 分钟前
【Keepalived】抢占模式、延迟抢占模式与非抢占模式详解
linux·运维·服务器·keepalived
sg_knight15 分钟前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式