122 Best Time to Buy and Sell Stock II

来源:互联网 发布:炉石传说盒子mac版 编辑:程序博客网 时间:2024/06/05 16:50
  • 122 Best Time to Buy and Sell Stock II

  • 题目描述:

    Say you have an array for which the i*th 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).

  • 题目大意:与121题类似,不同的是,此题可以多次买入卖出,但是不能同时买入卖出,要求最大收益。

  • 思路:贪心,遍历数组,寻找出第一个第一个非递减数字,则该数字之前的数字(如果存在的话)为当前买入股票的最小价格,从此数字遍历,找到递增数字的最后一个数,即比最小元素大的最大的元素,作为买入价格,两个数相减,即当前收益,继续从当前位置下一个位置遍历数组,直到数组被遍历完毕。

  • 示例,如给出[3,2,4,5,1,3],首先进行遍历,找出第一个非递减数字4,则2作为当前买入的最小价格,遍历数组,5为递增序列的最后一个数,所以当前收益为5-2=3,找到第二个非递减数字3,则其前一个数字1作为当前买入的最小价格,收益为3-1=2,

    最终收益为3+2=5。

  • 代码:

    package Array;public class Solution {    public static int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int i = 0;//        遍历数组        int profit = 0;        while (i < prices.length) {//            寻找最小元素            while (i < prices.length - 1 && prices[i + 1] <= prices[i]) {                i++;            }//            为最小元素赋值           int min = prices[i++];//            找出它大的元素最大元素            while (i < prices.length - 1 && prices[i + 1] >= prices[i]) {                i++;            }//            获取收益            profit += i < prices.length ? prices[i++]-min : 0;        }        return profit;    }
原创粉丝点击