leetcode 122. Best Time to Buy and Sell Stock II
2016-03-31 16:20
253 查看
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).
int maxProfit(int* prices, int pricesSize) {
if (prices == NULL)
return 0;
if (pricesSize < 2)
return 0;
int max = 0;
int k = 0;
while (k + 1 < pricesSize)
{
while (k + 1 < pricesSize&&prices[k] >= prices[k + 1])
k++;
int kk = k;
while (kk + 1 < pricesSize&&prices[kk + 1] >= prices[kk])
kk++;
max += prices[kk] - prices[k];
k = kk+1;
}
return max;
}
accepted
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).
int maxProfit(int* prices, int pricesSize) {
if (prices == NULL)
return 0;
if (pricesSize < 2)
return 0;
int max = 0;
int k = 0;
while (k + 1 < pricesSize)
{
while (k + 1 < pricesSize&&prices[k] >= prices[k + 1])
k++;
int kk = k;
while (kk + 1 < pricesSize&&prices[kk + 1] >= prices[kk])
kk++;
max += prices[kk] - prices[k];
k = kk+1;
}
return max;
}
accepted
相关文章推荐
- shell脚本实例
- 用rman同时备份到多个路径下
- 第1周 项目(A)-5求三个数的最大值
- java bridge
- IIS的安装与配置详细图解教程。
- java多线程细微知识点
- Duilib实现 Windows资源管理器前进后退原理
- iOS之 动态热修复技术JSPatch(二)
- 华为上机题-排号机
- 使用SAS/ACCESS For Oracle时字段长度映射翻倍问题
- VB简便15顺序
- java程序性能优化
- 如何搭建RMS并和SharePoint关联使用?
- Android 中Activity、Window和View之间的关系
- Unix Study之--AIX安装和配置SSH
- C++ STL 排序函数
- hdu1232畅通工程 并查集
- mac(linux) 上如何安装ant
- cursor
- Android Glide Google 推荐加载图片框架(加载图片详解篇)