【Best Time to Buy and Sell Stock II】cpp
2024-08-27 13:11:46
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if ( prices.size()== ) return ;
int sum_profits = , pre_price = prices[];
for ( size_t i = ; i < prices.size(); ++i )
{
sum_profits += (prices[i]>pre_price) ? prices[i]-pre_price : ;
pre_price = prices[i];
}
return sum_profits;
}
};
tips:
Greedy算法。
核心算法:如果当天的价格比前一天高,sum_profits就累加上当天的利润与前一天利润的差值(即昨天买,今天买);如果当天的价格比昨天低,则不更新sum_profits(即今天买,今天卖)。
========================================
第二次过这道题,低买高卖。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret = ;
for ( int i=; i<prices.size(); ++i )
{
if ( prices[i]>prices[i-] )
{
ret += prices[i]-prices[i-];
}
}
return ret;
}
};
最新文章
- 一步步开发自己的博客 .NET版(11、Web.config文件的读取和修改)
- Java实现多线程并发
- 阿里云日志api创建logStore
- CUBRID学习笔记 19 sql语句1
- 初学java之菜单条,菜单,菜单项的设置
- JavaScript高级程序设计(第三版)第三章 基本概念
- jeecms获取栏目标题图
- 和阿文一起学H5——音乐素材
- Memcache存储大数据的问题
- python 内置函数 getattr
- MyBatis学习总结2
- iOS进度指示器——NSProgress
- mysql用户修改登录密码及开启远程登录
- C语言递归回溯法迷宫求解
- TechSmith Camtasia Studio屏幕录像编辑工具
- Oracle timestamp类型转换成date类型
- RSF 分布式 RPC 服务框架的分层设计
- day22 os模块
- Java中equals()和hashCode()的关系以及重写equals()和hashCode()的重要性
- JSON自定义排序