最大收益
2016-06-01 16:02
387 查看
/*
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
*/
题意:
给定一系列价格(每天的),计算出最多能赚到多少钱,而且只能买卖一次。
多赚钱的原则就是低买高买,但要注意卖出一定要在买入之后。
* 方法一:只需要遍历一次价格。min=max=prices[0],不断置换最大的价格max,当出现比min小的价格时,计算这一轮的最大收益即max-min,如果比之前的收益更大,就更新最大收益。然后,重置min=price[i],max=min,开始新一轮的计算。最后,把max-min跟最大收益比较,返回最大收益。
#include <stdio.h>
int maxProfit(int* prices, int pricesSize) {
int min = prices[0], max = min;
int ret = 0;
for (int i = 1; i < pricesSize; i ++) {
if (min > prices[i]) {
ret = (max - min) > ret ? (max - min) : ret;
min = prices[i];
max = min;
}
else if (max < prices[i]) {
max = prices[i];
}
}
ret = (max - min) > ret ? (max - min) : ret;
return ret;
}
int main(int argc, char *argv[])
{
int arr[] = {5, 5, 6, 5, 4, 3, 5, 8, 3, 2, 5, 9};
printf("maxprofit: %d\n", maxProfit(arr, sizeof arr/sizeof arr[0]));
return 0;
}
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
*/
题意:
给定一系列价格(每天的),计算出最多能赚到多少钱,而且只能买卖一次。
多赚钱的原则就是低买高买,但要注意卖出一定要在买入之后。
* 方法一:只需要遍历一次价格。min=max=prices[0],不断置换最大的价格max,当出现比min小的价格时,计算这一轮的最大收益即max-min,如果比之前的收益更大,就更新最大收益。然后,重置min=price[i],max=min,开始新一轮的计算。最后,把max-min跟最大收益比较,返回最大收益。
#include <stdio.h>
int maxProfit(int* prices, int pricesSize) {
int min = prices[0], max = min;
int ret = 0;
for (int i = 1; i < pricesSize; i ++) {
if (min > prices[i]) {
ret = (max - min) > ret ? (max - min) : ret;
min = prices[i];
max = min;
}
else if (max < prices[i]) {
max = prices[i];
}
}
ret = (max - min) > ret ? (max - min) : ret;
return ret;
}
int main(int argc, char *argv[])
{
int arr[] = {5, 5, 6, 5, 4, 3, 5, 8, 3, 2, 5, 9};
printf("maxprofit: %d\n", maxProfit(arr, sizeof arr/sizeof arr[0]));
return 0;
}
相关文章推荐
- 软件测试技术之: 白盒测试和黑盒测试
- 《Linux总线、设备与驱动》USBHID设备驱动
- VS中MFC连接SQL SERVER
- Samba源码编译及安装
- 系统分析员考试复习笔记-2:第二章 经济管理与应用数学
- 面试中经常会被问到的70个问题
- win7 64位下安装ubtuntu双系统,默认windows7系统
- iOS IO 重定向(NSLog to UITextView)
- spark 基本方法
- android内存分析 outOfMemoryError错误定位及分析策略(非显示图片造成)
- 【leetcode】Majority Element
- BASE64加解密
- 九度OJ 1017
- 安卓开发前后台通信,从数据库中取数据并在前台以表格形式显示,以json格式传输
- Java判断访问设备为手机、微信、PC工具类
- 生成带链接的二维码
- lua math库
- spring TaskScheduler 来实现定时任务
- Spark机器学习API之特征处理(一)
- Reader开发(一)电子书分页,翻页效果,字体大小调整和基本功能实现