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;
}
相关推荐
玲娜贝儿--努力学习买大鸡腿版9 分钟前
hot 100 刷题记录(1)
数据结构·python·算法
兮℡檬,27 分钟前
答题卡识别判卷
开发语言·python·计算机视觉
酉鬼女又兒30 分钟前
零基础快速入门前端DOM 操作核心知识与实战解析(完整汇总版)(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯·js
123过去34 分钟前
pixiewps使用教程
linux·网络·测试工具·算法·哈希算法
kyle~37 分钟前
C++----函数指针与函数指针类型 返回值类型 (*类型名)(参数列表)
开发语言·c++
深圳市快瞳科技有限公司40 分钟前
低空经济下,鸟类识别算法与无人机硬件的兼容性优化策略
算法·无人机
努力中的编程者1 小时前
二叉树(C语言底层实现)
c语言·开发语言·数据结构·c++·算法
H_老邪1 小时前
Linux 与 Docker 常用命令
linux·运维·服务器·docker
大尚来也1 小时前
PHP 反序列化漏洞深度解析:从原理利用到 allowed_classes 防御实战
android·开发语言·php
鹤旗1 小时前
While语句,do-while语句,for语句
java·jvm·算法