leetcode Best Time to Buy and Sell Stock II

来源:互联网 发布:php动态网页设计 编辑:程序博客网 时间:2024/06/05 11:03

Best Time to Buy and Sell Stock II

 Total Accepted: 4391 Total Submissions: 12451My Submissions

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


We should buy the stock at the starting point of ascending status, and sell the stock at the ending point of ascending status. The code is :

class Solution {public:    int maxProfit(vector<int> &prices) {        // Note: The Solution object is instantiated only once and is reused by each test case.        int minP,i,j,res=0,buy,sell;        if(prices.size()==0)            return 0;        else{            buy=prices[0];            for(i=0;i<prices.size();i++){                if( i+1<prices.size()&&prices[i+1]<prices[i] ){                    res+=prices[i]-buy;                    buy=prices[i+1];                }            }            res+=prices[prices.size()-1]-buy;         }        return res;    }};


原创粉丝点击