您的位置:首页 > 其它

122. Best Time to Buy and Sell Stock II

2018-01-05 13:34 281 查看
问题

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

2.描述

这道题着实把我坑到了,先描述一下题意就是给定一个数组,数组是每天股票的价格,需要确定最大的收益是多少,一开始思想我就直接搞成排序了,哈哈找到最大值与最小值的查 -。-
后来改成寻找每个数字的下一个大的值,放进Map,然后根据遍历数组,找到低买高出整条线路,然后比较全部线路的最大收益。比较麻烦!!
后续改为只要从头开始进行判断然后比较下一个值如果下一个值较大则前一个值买入,最大值卖出,然后进行依次递进。


代码

class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 0; i < prices.length - 1; ++i) {
if (prices[i] < prices[i + 1]) {
res += prices[i + 1] - prices[i];
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: