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;
}
相关推荐
菜菜的顾清寒几秒前
力扣HOT100(35)回溯-全排列
算法·leetcode·职场和发展
week@eight几秒前
Linux - Kafka
linux·kafka
Zhang~Ling1 分钟前
C++ 多态完全指南:虚函数、重写、虚表与动态绑定深度解析
开发语言·c++
BestOrNothing_20152 分钟前
C++零基础到工程实战(5.2.5):函数默认参数和函数重载
c++·函数重载·函数默认参数·nullptr·函数声明与定义
不负岁月无痕2 分钟前
STL-- C++ list类 模拟实现
开发语言·c++·list
weixin_468466855 分钟前
目标识别算法落地实战:从选型到部署的全流程指南
图像处理·人工智能·python·算法·目标检测·机器视觉·目标识别
MicroTech20256 分钟前
微算法科技(NASDAQ :MLGO)量子启发进化算法(QEA)与区块链(BC)集成技术:构建高可靠去中心化创新方案
科技·算法·量子计算
JSON_L7 分钟前
PHP 高精度计算完全指南:彻底解决浮点数精度丢失
开发语言·php
CQU_JIAKE8 分钟前
5.27【A】
算法
weixin_456808389 分钟前
【沁恒蓝牙开发】主机-筛选广播名主动发起连接
c语言·嵌入式硬件