博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode-122] Best Time to Buy and Sell Stock II
阅读量:5167 次
发布时间:2019-06-13

本文共 2518 字,大约阅读时间需要 8 分钟。

Best Time to Buy and Sell Stock II

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).

 

不要想太多,就是整个波动中所有上升曲线的和。

 

1 class Solution { 2     public: 3         /* 大数据集妥妥的超时的暴力方法,啊!太傻了!捉急啊!!! 4         int result; 5   6         void getMaxProfit(int buy_price, int day_start, int profit_before, const vector
& prices) { 7 if (day_start == prices().size()) { 8 if (profit_before > result) { 9 result = profit_before;10 return;11 }12 }13 for (int i = day_start; i < prices.size(); ++i) {14 if (prices[i] < buy_price) {15 getMaxProfit(prices[i], i + 1, profit_before, prices); // 买16 getMaxProfit(buy_price, i + 1, profit_before, prices); // 不买17 } else {18 getMaxProfit(INT_MAX, i + 1, profit_before + prices[i] - buy_price, prices); // 卖19 getMaxProfit(buy_price, i + 1, profit_before, prices); // 不卖20 }21 }22 }23 24 int maxProfit(vector
&prices) {25 // Start typing your C/C++ solution below26 // DO NOT write int main() function27 result = 0;28 getMaxProfit(INT_MAX, 0, 0, prices);29 return result;30 }31 */32 33 int maxProfit(vector
&prices) {34 // Start typing your C/C++ solution below35 // DO NOT write int main() function36 // 所有上升线段长度和......37 if (0 == prices.size()) {38 return 0;39 }40 int max_profit = 0, last_min = prices.at(0);41 for (int i = 1; i < prices.size(); ++i) {42 if (prices.at(i) < prices.at(i - 1)) {43 max_profit += (prices.at(i - 1) - last_min);44 last_min = prices.at(i);45 }46 }47 max_profit += (prices.at(prices.size() - 1) - last_min);48 return max_profit;49 }50 };
View Code

 

转载于:https://www.cnblogs.com/leon-wang/p/3288322.html

你可能感兴趣的文章
Python acos() 函数
查看>>
top coder password题解
查看>>
Myeclipse 安装所有插件
查看>>
4-1
查看>>
POJ - 2796 Feel Good 单调递增栈+前缀和
查看>>
redis面试题
查看>>
三、activiti designer 的安装
查看>>
Python自省
查看>>
How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
查看>>
【算法】求二叉树各路径结点之和并找出最大值的路径
查看>>
c 字符串 函数
查看>>
12.5 站立会议
查看>>
SQLServer数据库的一些全局变量
查看>>
Centos-本机网络连接、运行端口和路由表等信息-netstat
查看>>
胡适阅读
查看>>
Java中日期的转化
查看>>
小程序弱网环境卡顿怎么办?一招迅速提升小程序运行速度
查看>>
管线【十八】
查看>>
重温设计模式 - 建造者模式
查看>>
Android开发 LevelListDrawable详解
查看>>