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;
}
相关推荐
大大杰哥6 分钟前
Java 日志框架详解:SLF4J + Logback 从入门到实战
java·开发语言·logback
coward9111 分钟前
Linux内核驱动初始化流程认识(关于late_initcall和modul_init驱动初始化宏差异)
linux·嵌入式硬件
ylscode13 分钟前
黑客利用 GHOSTYNETWORKS 和 OMEGATECH 托管 JS 恶意软件基础设施
开发语言·安全·php·安全威胁分析
modelmd13 分钟前
Linux man 命令详解:从入门到精通
linux
莫等闲-14 分钟前
leetcode42. 接雨水 leetcode84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
爱吃生蚝的于勒14 分钟前
QT开发第二章——信号和槽
c语言·开发语言·c++·qt
unicrom_深圳市由你创科技14 分钟前
历史数据存储量太大,怎么处理?数据压缩/归档策略?
算法
浅念-15 分钟前
LeetCode 记忆化搜索 刷题总结
数据结构·算法·leetcode·职场和发展·深度优先·dfs
xcLeigh19 分钟前
Python入门:Python3 operator模块全面学习教程
开发语言·python·学习·教程·python3·operator
大叔带刺21 分钟前
使用python创建自己的专属星座签名APP:Name2Constell
开发语言·python·pygame