[leetcode] 122. Best Time to Buy and Sell Stock II

来源:互联网 发布:腾讯云域名怎么添加 编辑:程序博客网 时间:2024/05/22 10:40

题目:
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).

思路:根据题目,可知应该在能够获益的前提下进行足够多的交易。
具体的问题是每次交易 什么时候买入,什么时候卖出?
买入时间:在数组中只要后面一个的数字比当前数字大就可以买入,
卖出时间:在数组中后一个数字比当前数字小时才卖出
因为题目中规定同时不能进行多次交易,并且必须满足买在卖之前。

举例:prices数组   [1, 2, 3, 5, 2, 4]
1)从数组第0个位置开始比较: prices[0] < prices[1]可以以prices[0]的价格买入
2)依次进行 比较 prices[1] < prices[2] 此时手中有股票 不需要买入,但是之后prices[2]的价格比prices[1]的价格高,所以也不需要卖出;
3)再比较prices[2] < prices[3]与2)中情况相同 不进行任何操作(买入或卖出) ;
4)再比较prices[3] > prices[4]此时 应该卖出才是当前获益最高,故卖出
5)再比较prices[4] > prices[5]此时满足买入条件且手中没有股票 故买入
6)在最后时应为手中有股票 所以最后卖出

具体代码如下:

public class Solution {    public int maxProfit(int[] prices) {        int result = 0;//存储最终结果        int len = prices.length;        if(len == 0){            return 0;        }        boolean flag = false;//作为判断当前是否有股票在手的标志 false表示手中没有股票        int buy = 0;//一次交易中买入的价格        int sale = 0;//一次交易中卖出的价格        //因为都是与数组中的后一个数进行比较 为保证不越界 所以i只能递增到len-1        for(int i = 0;i < len - 1; i++){            int num1 = prices[i];            int num2 = prices[i+1];            if(num1 < num2 && flag == false){//如果此时满足买入条件且手中没有股票                buy = num1;//买入                flag = true;//把手中是否有股票的状态设置成true(有股票的状态)            }            if(num1 > num2 && flag == true){//如果满足卖出的条件 且手中有股票                sale = num1;//卖出                result = result + sale - buy;//收益累加                flag = false;//把手中是否有股票的状态设置成false(没有股票的状态)            }        }        //前面比较到数组的len-1的位置处 最后需要判断此时是否手中有股票 如果有在最后一天需要卖掉        if(flag == true){            result = result + prices[len-1] - buy;        }        return result;    }}
0 0
原创粉丝点击